检查是否填充了其中一个文本框 - Jquery

时间:2015-08-12 13:23:11

标签: jquery html

从下面的HTML和JQuery中,我试图检查文本框中是否至少有一个值。它运作得很好。

我想知道是否有更好更短的方法来实现同样的目标。

HTML

<div id="content">
    <input type="text" id="text1"/>

     <input type="text" id="text2"/>

     <input type="text" id="text3"/>

     <input type="text" id="text4"/>

    <input type="text" id="text5"/>

    <button onclick="checker();" >Check</button>        
    </div>

Jquery的

function checker(){

    var text1 = $('#text1').val().length;
    var text2 = $('#text2').val().length;
    var text3 = $('#text3').val().length;
    var text4 = $('#text4').val().length;
    var text4 = $('#text4').val().length;
    var text5 = $('#text5').val().length;

    if (text1==0 && text2==0 && text3==0 && text4==0 && text5==0)            
    {            
         alert('atleast one of the field should be filled');   
    }
}

小提琴

https://jsfiddle.net/uaLxfrqc/2/

4 个答案:

答案 0 :(得分:3)

您可以更好地实现这一目标:

X

<强> Working Demo

答案 1 :(得分:1)

只需将“textboxes”类添加到每个输入类型中,并使用此经过测试的工作代码段迭代它们。

function checker(){
var bool = false;


$('.textboxes').each(function() {
  if (!$(this).val() == '') {
       bool = true;
  }
   });
    alert(bool)
}

Link用于演示。

答案 2 :(得分:0)

这也有效:

var isEmpty= false;
$("input[type=text]").each(function() {
      if($(this).val().length > 0)
         {
            isEmpty = true;
            return false; //break out of the loop
         }
});  


if(!isEmpty ){
   alert('atleast one of the field should be filled');  
} 

这是DEMO

答案 3 :(得分:0)

试试这个,虽然还没有测试过,

function checker(){
    var x="";
    $("input[type='text']").each(function(){
        if($(this).val()=="")
            x=x+"y";
    });

    if(x.length>0)            
    {            
         alert('atleast one of the field should be filled');   
    }
}