Mike Barwick
Mike Barwick

Reputation: 5367

I have this jQuery Validation function issue. Validation only works once

The function below works as it should. It's to validate a form. In short, I have a couple input fields. If I hit submit and no text has been entered in either input, the validation errors appear. If I fill in one field, only one of the fields will update. But if I hit "submit" again, even without filling in the second form input, the else{} gets fired, not the if{} that should assure it's filled out, etc.

Not familiar, but is it a return false; issue?

if ($('input[type="text"]:visible').val().length == 0) {
    $('.submitModal').click(function () {
        $('.modal').modal('show'); 
    });
}
else {
    $('.submitModal').click(function () {
        $('.modal').modal('hide'); 
    });
}

Any idea what Im doing wrong?

Upvotes: 1

Views: 622

Answers (1)

Greg Pettit
Greg Pettit

Reputation: 10830

This is backwards thinking. Bind the click, period. Not conditionally. On click, decide what you want to happen (even if this just means ignoring the click).

If you do bind a click, filling out the form differently isn't going to unbind it. And even though you COULD actually unbind it, there's no great reason to.

If .submitModal is actually a submit input element (rather than an anchor or button with that class), instead of binding a click listener, bind a submit listener.

Based on Mike's own starting point of code, here's an example (slightly outside the true context, since I don't have the modal function available without unecessary effort!)

$('.submitModal').click(function (e) {
    e.preventDefault();
    $('input[type="text"]:visible').each(function() {
        if ($(this).val().length == 0) {                        
            $('.modal').show();                        
        }
        else {
            $('.modal').hide();
        }
    });
});​

The first thing that's different is that I pass the event into the click handler, and then preventDefault on it. That prevents the anchor from causing a page refresh.

But the only other thing I did is swap out the actual .modal() call for a generic jQuery .show() and .hide() just to proof-of-concept the logic.

Mike, the sample code you wrote was pretty much bang-on (except the preventDefault assuming you do in fact want to prevent default anchor behaviour). Here's the proof:

jsfiddle.net/gnaXn/2

When all visible text fields are filled in, the "modal" hides. When they're emptied again, the "modal" reappears.

Upvotes: 1

Related Questions