views:

44

answers:

3

I have a form that is validated once the user "blur"s out of an input field. So:

$("#field1").blur(function() {

if($(this).val().length>0) {
   $(this).attr('class', 'completed');
}

});

When the user first visits the form, and up until all fields are "completed", the submit button is hidden:

$(".submit").hide();

I want the submit button to slideDown once all #field1, #field2 ... elements have been assigned a "completed" class (any other method suggested will work as well).

I tried using:

$("#field1").blur(function() {
    if($(".completed").length == $("input[type='text']").length) {
        $(".submit").slideDown(1000);
    }
});

But it didn't work as it was called concurrently with the previous "blur" handler.

Is there a method to bind an event handler to after another has triggered? Maybe a way to add a callback function to "blur" that works?

I'd appreciate all types of solution (not necessarily somethin like I presented).

+1  A: 

Just do your check inside of your first .blur method, though I would suggest using a class name to prevent any other inputs on the page interfering.

$(".input-field").blur(function() {
  if($(this).val().length>0) {
   $(this).addClass('completed');
  }
  setTimeout("isFormValid()", 100);
});

function isFormValid() {
  if($(".completed").length == $(".input-field").length) {
    $(".submit").slideDown(1000);
  }
}
Marko
that doesn't work because both addClass and if statement seem to happen concurrently, so by the time if is executed, the last input field hasn't been assigned a "completed" class.
sombe
Ahh of course - I've added a setTimeout function which will run 100ms after the if statement, try that and see if it helps.
Marko
+2  A: 

Well, you don't necessarily need to set css classes for doing these kind of validations:

$("#field1").blur(function() {
    if($("input[type='text']"),filter(isCompleted).length == $("input[type='text']").length) {
        $(".submit").slideDown(1000);
    }
});

function isCompleted(i) {
    return $(this).val().length > 0;
}

Another way could be:

$("#field1").blur(function() {
    // If there are not empty textboxes, slidedown...
    if($(":text[value='']").length === 0) {
        $(".submit").slideDown(1000);
    }
});
Matias
A: 

How about something like:

$('input').blur(function() {
  if (this.value.length > 0)
    $(this).addClass('validationError');
  else
    $(this).removeClass('validationError');

  validateForm($(this).parents('form'));
});

funciton validateForm($form) {
  if ($form.has('.error').length > 0)
    $('.submit').slideUp();
  else
    $('.submit').slideDown();
}
Dave Ward