Reputation: 23662
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).
Upvotes: 0
Views: 3777
Reputation: 60580
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();
}
Upvotes: 0
Reputation: 5348
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);
}
});
Upvotes: 3
Reputation: 72222
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);
}
}
Upvotes: 1