javascript - check whether text field is empty or not jquery - Stack Overflow

I have a div which contain lots of input[type=text] fields. I want to put a check that user must have f

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 ?

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 ?

Share asked Jul 5, 2012 at 9:49 Tom RiderTom Rider 2,8157 gold badges44 silver badges66 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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.

The standard way

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742296509a4417230.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信