Tom Rider
Tom Rider

Reputation: 2805

check whether text field is empty or not jquery

I have a div which contain lots of input[type=text] fields. I want to put a check that user must have fill all the fields otherwise show error message. For this i tried :

if ($('div').children("input[type=text]").attr("value") == '') 
 flag = false; 
else 
 flag = true;

But this will not check all the text field, it only checks the first-child . How can i check all the text field ?

Upvotes: 3

Views: 9880

Answers (3)

h0mayun
h0mayun

Reputation: 3601

if($("div").find('input:text[value=""]').length > 0)
{
 alert("error");
 return false;
}

Upvotes: 0

antyrat
antyrat

Reputation: 27765

Try to use find() instead

 if ($('div').find("input[type=text]").val() == '')

To check over all input items you need to iterate over them using each().

Correct code would be:

$(function() {
    $('input:submit').click(function(){
        var flag = true;
        $('div').find("input[type=text]").each(function(){
            if($(this).val() === '') flag = false
        });

        alert(flag);
    });
});​

See demo on jsFiddle.

This code return true if all input[type=text] fields inside div are filled and false if at least one is empty.

Upvotes: 3

coolguy
coolguy

Reputation: 7954

The standard way

if(!$('div').find('#idOfTextField').val()){
 //empty
}

Upvotes: 1

Related Questions