Radu Dascălu Radu Dascălu - 1 year ago 217
Javascript Question

jQuery: Button submits form only after two clicks

I am making a form validation function, and if there are no empty input's the button takes two clicks to work correctly.

This is my function:

function validate(root, animation, error) {
$('.button').on('click', function(event) {

var isEmpty = false,
root = $(root),
animation = animation ? animation : 'animation animation-shake',
error = error ? error : 'error';

root.find('form').find('.required').each(function() {
if ($(this).val().length == 0) {
isEmpty = true;
$(this).addClass(error).on('keydown', function() {

if (isEmpty) return;

The code that calls the function:

validate('#login-box .box');

Any ideas would be great, also suggestions about how to shorten/improve the code.

Answer Source

Your method should be:

function validate(root, animation, error) {
    $('.button').on('click', function(event) {
        /* event.preventDefault();*/ //<< remove it
        var isEmpty    = false,
        /*if (isEmpty) return;
          $(this).unbind('click');*/ //<< remove it

        // and set at handler bottom   
        if (isEmpty) event.preventDefault();

Only prevent submit behaviour when needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download