1 回答

TA貢獻1827條經驗 獲得超8個贊
該document.getElementById函數返回一個節點,而不是來自輸入的值。您需要調用value這些節點上的屬性來訪問它們的值。
function ansValidation(ev) {
ev.preventDefault
// there is no input named name
//var nameValue = document.getElementById("name").value
var nameValue = "test";
var passValue = document.getElementById("password").value
var confpassValue = document.getElementById("confirmPassword").value
// the typeof operator returns a string.
if(typeof nameValue !== "string"){
window.alert("Please re-enter your name")
// we use strict validation ( !== ) because it's a good practice.
}else if(passValue !== confpassValue) {
window.alert("Passwords do not match!")
}
}
<form>
Password:<br>
<input type="password" id="password" placeholder="Password">
<br>
Re-enter Password:<br>
<input type="password" id="confirmPassword" placeholder="Confirm password">
<br>
<input type="button" href="#" onclick="ansValidation(event)" value="Sign Up">
</form>
我還編輯了您的代碼以使其在代碼段中工作。這是它遇到的一些問題。
id=""
如果要使用該getElementById
函數,則需要將屬性傳遞給輸入輸入
name
不存在運算符
typeof
返回一個字符串,您需要將其與字符串進行比較。在 Javascript 中比較事物時,嚴格比較事物 (
===
)始終是一個好習慣。我已將事件添加到函數中,
ev.preventDefault
以確保在發送表單之前正確完成驗證。
添加回答
舉報