user1124535
user1124535

Reputation: 845

Checking input fields on page load?

How do I check all input boxes to see if there are values when the document loads?

$(document).ready(function(){
   var inputVal=$("input").val().trim();
   if(inputVal!=''){
   }
})

I would like to do an action for any input boxes that have values.

Upvotes: 1

Views: 6484

Answers (4)

David Thomas
David Thomas

Reputation: 253396

This is one way:

$('input, select, textarea').each(
    function(){
        var val = $(this).val().trim();
        if (val == ''){
            // do stuff with the non-valued element
        }
    });

On closer reading it seems the OP wanted to do something with the non-empty fields, so:

$('input, select, textarea').each(
    function(){
        var val = $(this).val().trim();
        if (val.length){
            // do stuff with the valued element
        }
    });

Upvotes: 6

charlietfl
charlietfl

Reputation: 171690

Another approach to create a jQuery object of inputs that do have value

$("input").filter(function(){
    return $(trim(this.value)) !='';                      
}).doSomething();

Upvotes: 1

DG3
DG3

Reputation: 5298

you can do a loop on all the inputs with type="text'.

 $("input[type='text']").each(function(){
   alert($(this).val()); 
});

The sample html is as follows

​<input type="text" name="input1" value="2"/>
<input type="text" name="input2" value="4"/>
<input type="text" name="input3" value="5"/>​

If you want to include select, or other input elements in the loop, you can do what David Thomas has suggested

Upvotes: 0

Alex
Alex

Reputation: 35407

var fields = $("input, textarea, select"), i = 0;

for(i; i < fields.length; i++){
    if(fields.eq(i).val() !='') { /* ... logic ... */ }
}

Upvotes: 1

Related Questions