所以事情就是这样,我正在学习 JS,我开始做一些简单的练习来熟悉它,所以我尝试做一个简单的表单验证,但我遇到了显示错误的 div 的问题,因为它们是被覆盖,我想得到一些建议来改进这个代码,如果可能的话让它变得更好。谢谢 !
function checkdata() {
//Acess TextBox Content
var name1 = document.getElementById("name1").value;
var name2 = document.getElementById("name2").value;
var email = document.getElementById("email").value;
//Acess Radio Content
var tdi = document.getElementById("tdi");
var tri = document.getElementById("tri");
var tsi = document.getElementById("tsi");
//Acess Checkbox
var ch = document.getElementById("terms").checked;
//Functions
if (name1 == "" || name2 == "" || email == "") {
document.getElementById("errorsdiv").innerHTML = "Those Fields Are Required";
}
if ((tdi.checked == false) || (tri.checked == false) || (tsi.checked == false)) {
document.getElementById("errorsdiv").innerHTML = "You need to check one branch";
}
if (ch.checked == false) {
document.getElementById("errorsdiv").innerHTML = "You need to Agree on our terms";
}
}
<h1>Form Validation</h1>
<form>
<fieldset>
<legend>Informations</legend>
<label for="name1">Enter Your First Name</label>
<input type="text" id="name1"><br>
<label for="name2">Enter Your Last Name</label>
<input type="text" id="name2"><br>
<label for="email">Enter Your email</label>
<input type="text" id="email"><br>
<label>Choose Your Branch : </label>
<label for="tdi">TDI</label>
<input type="radio" name="branch" id="tdi">
<label for="tri">TRI</label>
<input type="radio" name="branch" id="tri">
<label for="tsi">TSI</label>
<input type="radio" name="branch" id="tsi"><br>
<input type="checkbox" name="terms" id="terms">
<label for="terms">Agree On Our Terms</label>
</fieldset><br>
<input type="button" value="Submit" class="button" onclick="checkdata();">
<fieldset class="errorsf">
<legend>Errors</legend>
<div class="errorsdiv" id="errorsdiv">
</div>
</fieldset>
</form>