簡體   English   中英

代碼片段不起作用

[英]Snippet of code not working

下面是表單驗證腳本的簡化代碼片段。 這是行不通的...

提交表單並且用戶將“inputfield”留空時,會彈出第一個警報。 用戶在“inputfield”中輸入內容后,當用戶單擊“提交”時,會彈出第二個警報。

之后,腳本應返回false並繼續驗證。 我需要將兩個警報包括在同一個其他內容中。 我究竟做錯了什么? 警報沒有顯示,表單驗證忽略了這部分代碼......

    } else if (myform.inputfield.value=="") {
    alert ('Please enter something in the text field!');
    }
    if (myform.inputfield.value!=="") {
    alert ('Thank you for entering something in the field!');
    return false;
    }

我同意使用document.getElementById或jQuery $('#input1')。val()

 <script type="text/javascript">
    function validate() {
        if (document.getElementById('input1').value == "") {
            alert('Please enter something in the text field!');
        }
        if (document.getElementById('input2') !== "") {
            alert('Thank you for entering something in the field!');
            return false;
        }
    }
</script>
</head>
<body>
    <form onsubmit="return validate()">
        <input id="input1" />
        <input id="input2" />
        <input type="submit" value="OK" />
    </form>
</body>

您可能在指定的代碼行之前有一個return語句?

聲明一個標志並返回它是不是更好? 考慮以下示例:

var validationResult = true;

...
} else if (myform.inputfield.value=="") {
   validationResult = false;
   alert ('Please enter something in the text field!');
}
if (myform.inputfield.value!=="") {
   alert ('Thank you for entering something in the field!');
   validationResult = false;
}

return validationResult;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM