Reputation: 39
I am developing a multipage form. I am trying to write an if
condition:
$('.next').click(function() {
if ($('input[required]:visible').each().val() == false) {
alert('Not all required fields are filled');
} else {
$('.next').show();
$('form.idealforms').idealforms('nextStep');
}
});
This works fine with input type=text
. Then I am trying to add the same condition for <textarea>
:
$('.next').click(function() {
if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
alert('Not all required fields are filled');
} else {
$('.next').show();
$('form.idealforms').idealforms('nextStep');
}
});
Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?
Upvotes: 1
Views: 121
Reputation: 1423
You should trim
the value before comparing.
Below is the code to handle required inputs (for checkbox, radio button different handling will require).
$('.next').click(function() {
var valid = true;
$.each($('[required]:visible'), function() {
if (!$.trim($(this).val())) {
valid = false;
return false;
}
});
if (!valid) {
alert('Not all required fields are filled');
} else {
alert('All required fields are filled');
}
});
Upvotes: 1
Reputation: 1751
jQuery .val()
gives you the content of Textbox or Textarea, not Boolean. So you can use jQuery .trim().length
. It will first remove the white space and then it counts the length of Textbox or Textarea.This ensures that even space is there, it will work. Working fiddle
$('.next').click(function(){
if($('input[required]:visible').val().trim().length==0 || $('textarea[required]:visible').val().trim().length==0) {
alert('Not all required fields are filled');
}
else{
alert('All required fields are filled');
}
});
Upvotes: 1
Reputation: 3033
In your jsFiddle, you have content in the textarea
(empty spaces). I think your best bet would be to trim the values before checking them and then comparing them to the empty string ''
.
if ($('input[required]:visible').val().trim() == '' || $('textarea[required]:visible').val().trim() == '') {
...
}
Also, I changed your and
to an or
, which is what I think you need.
Upvotes: 3