Reputation: 1474
I would like to check if the form's inputs have a value once the page loads for the first time. If so, then add a class.
Here's my code so far,
if( $('input').val() ) {
$(this).addClass("correct");
}
Do I need to be checking for length? Here's the fiddle, http://jsfiddle.net/SFk3g/ Thank you
Upvotes: 1
Views: 3390
Reputation: 9851
Updated fiddle:
// Select all input elements, and loop through them.
$('input').each(function(index, item){
// For each element, check if the val is not equal to an empty string.
if($(item).val() !== '') {
$(item).addClass('correct');
}
});
You can select all input elements, and loop through them, then apply your check. In this case, you have just mentioned to check if they are empty - this allows you to add additional checks as required by your business logic as required.
Upvotes: 1
Reputation: 298364
If serverside code isn't an option, you can use filter
:
$('input').filter(function() {
return this.value;
}).addClass('correct');
A plain selector might also work:
$('input[value!=""]').addClass('correct');
Upvotes: 4