2016-05-29 110 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

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