我仍然在学习JavaScript,但尝试为某些最终用户构建一些表单验证,以便根据某些变量不能将字段设置为空。
这是我的相关代码。
function validateForm() {
var a = document.forms["myForm"]["Joint_1"].value;
var b = document.forms["myForm"]["ID_1"].value;
var c = document.forms["myForm"]["ID_2"].value;
if (a == "Y" && b == "" && c == "") {
console.log("Account is indicated to be joint, either one or both instances of ID is incomplete");
return false;
}
if (a == "N" && b == "") {
console.log("ID is incomplete for a single owner");
return false;
}
}

.a {
display: table-row;
}
.a div {
display: table-cell;
padding: 5px;
}

<form name="myForm" onsubmit="return validateForm()" method="post">
<div class="a">
<div class='a'>
<div>Joint Account?:</div>
<div><select id="unit" size="1" name="Joint_1">
<option disabled="disabled" selected="selected" value=""></option>
<option value="Y">Y</option>
<option value="N">N</option>
</select></div>
</div>
</div>
<div class="a">
<div>ID:</div>
<div><input type="text" name="ID_1" size="12" maxlength="12"></div>
</div>
<div class="a">
<div>ID:</div>
<div><input type="text" name="ID_2" size="12" maxlength="12"></div>
</div>
<div class='a'>
<div><input type="submit" value="Save"></div>
<div> <input type="reset" value="Reset"></div>
</div>
</form>
&#13;
Joint_1
将永远不会是空字符串,因为它将从其他地方继承其值。
该表单适用于Joint_1 == "Y"
以及ID_1 == ""
和ID_2 == ""
。
但是,当Joint_1 == "Y"
和ID_1
或ID_2
不是空字符串时,表单将提前而不是生成警报。必须在&#34; Y&#34;的实例中填写ID_1
和ID_2
。 Joint_1
中的值。
有没有办法完成此操作,以便在Joint_1 == "Y"
以及ID_1 == ""
或ID_2 == ""
时生成警报?我尝试使用or(||
)运算符,但后来我在Joint_1 == "N"
逻辑上失败了。
答案 0 :(得分:0)
function validateForm() {
var a = document.forms["myForm"]["Joint_1"].value,
b = document.forms["myForm"]["ID_1"].value,
c = document.forms["myForm"]["ID_2"].value;
if (a === "Y" && (b === "" || c === "")) {
alert("Account is indicated to be joint, either one or both instances of ID is incomplete");
return false;
} else if (a === "N" && b === "") {
alert("ID is incomplete for a single owner");
return false;
}
}
作为最佳做法,您可能需要考虑使用===
(身份)代替==
(等于)进行比较 - {{ 3}}