Richard
Richard

Reputation: 1474

jQuery, checking to see if <input> has a value when first loading the page

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

Answers (2)

Alex Osborn
Alex Osborn

Reputation: 9851

Updated fiddle:

http://jsfiddle.net/yhwYQ/

// 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

Blender
Blender

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

Related Questions