如果已标识的DOM元素之一为空,则将背景色更改为红色,否则将背景色更改为透明。为什么这在电话或位置字段上不起作用?
我还有另一个针对诸如document.forms [“ pledge”] [“ position”]之类的元素的脚本,它也适用于除电话和位置之外的所有其他字段。我想念什么?
function checkFilled() {
var fname = document.getElementById("fname"),
lname = document.getElementById("lname"),
email = document.getElementById("email"),
country = document.getElementById("country"),
zip = document.getElementById("zip"),
position = document.getElementById("position"),
phone = document.getElementById("phone");
;
if (fname.value != "") {
fname.style.backgroundColor = "transparent";
} else {
fname.style.backgroundColor = "red";
}
if (lname.value != "") {
lname.style.backgroundColor = "transparent";
} else {
lname.style.backgroundColor = "red";
}
if (email.value != "") {
email.style.backgroundColor = "transparent";
} else {
email.style.backgroundColor = "red";
}
if (country.value != "") {
country.style.backgroundColor = "transparent";
} else {
country.style.backgroundColor = "red";
}
if (zip != undefined && zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
if (position.value != "") {
position.style.backgroundColor = "transparent";
} else {
position.style.backgroundColor = "red";
}
if (phone.value != "") {
phone.style.backgroundColor = "transparent";
} else {
phone.style.backgroundColor = "red";
}
}
的HTML
<form name="pledge" id="form">
<input class="input" type="text" id="fname" name="first_name" placeholder="First Name" onchange="checkFilled()">
<input class="input" type="text" id="lname" name="last_name" placeholder="Last Name" onchange="checkFilled()">
<input class="input" type="text" id="position" name="user_position" placeholder="Position in Government" onchange="checkFilled()">
<input class="input" type="text" id="country" name="user_country" placeholder="Country" onchange="checkFilled()">
<input class="input" type="email" id="email" name="user_email" placeholder="Official Government Email" onchange="checkFilled()">
<input class="input" type="number" id="phone" name="user_phone" placeholder="Office Phone Number" onchange="checkFilled()">
<input class="input full-width" type="submit" value="Take The Pledge!">
</form>
https://codepen.io/froggomad/pen/maRJxr
该脚本失败,因为它试图处理该表单上不存在的zip元素。我错误地尝试通过检查条件是否存在并包含一个值,然后如果两个条件都不成立(OOPS)来更改其背景颜色,来处理该条件
工作守则
if (zip != undefined) {
if (zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
}
您的表单没有带zip
id的元素,因此尝试zip
在zip
检查的else语句中修改style属性会引发错误null
。由于该错误导致函数失败,因此基于position
andphone
的if语句不执行。
如果删除if/else
检查zip
变量的块,则这两个字段将再次起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句