Radu Dascălu Radu Dascălu - 2 months ago 6
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) {
event.preventDefault()

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;
root.addClass(animation);
$('.required.error:first').focus();
$(this).addClass(error).on('keydown', function() {
$(this).removeClass(error);
root.removeClass(animation);
});
}
});

if (isEmpty) return;
$(this).unbind('click');
});
}


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

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.