2016-05-29 175 views
-1

我正在尝试查找空输入字段!验证输入字段

<div style="float: left; margin: 5px;"> 
    <p style="margin-left: 50%;">x</p> 
    <input id="myInput1" type="number"> 
    </div> 

    <div style="float: left; margin: 5px;"> 
     <p style="margin-left: 50%;">y</p> 
     <input id="myInput2" type="number"> 
    </div> 

    <button style="margin-top: 55px;" onclick="validate1()">some things</button> 

    <script> 

    function validate1(){ 
    var one = document.getElementById("myInput1").value; 
    var two = document.getElementById("myInput2").value; 
    if(one == null) 
    alert("missing data in x"); 
    else if (two == null) 
    alert("missing data in y"); 
    else 
    alert("yes, it works"); 
} 
     </script> 

请大家帮忙!:)它并不显示在输入字段为空 什么不好??? 我试图找出如果输入字段为空

+0

为什么'一个== null'?改用'one ===“”'。 –

回答

0

one == null告诉你,如果onenullundefined,但如果输入字段为空,则.value是空字符串,而不是null也不undefined

相反,你应该使用类似

if(one === '') // compare with empty string directly, I recommend this 

if(!one) // check if "falsy" (which for strings mean empty) 

if(one.length === 0) // check if string has no length 
+0

谢谢,快速回答:) :) –