[英]How to do proper validation for this and set focus and then form has to submitted
在這里,我面臨的一個問題是,如果條件能夠對主題進行驗證,並且無法設置焦點並且無法對中場進行驗證。 這里的復選框來自mysql。 但是它僅提供這樣的源。 任何人都可以找出我的代碼中的問題嗎?我必須在這里做什么。我希望每個人都明白這個問題。我需要適當的代碼來驗證這兩個字段。 至少在主題列中,應該在區域字段中同樣選擇任何一個,也應該選擇任何一個。 我嘗試了很多事情。 但是我無法完成工作。
我需要的是:
<script type="text/javascript">
function check() {
var a1 = false;
b1 = false;
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var reg1 = reg.length;
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
a1 = true;
}
}
}
if (!chk[i].checked) {
chk[i].focus();
}
if (len) {
for (i = 0; i < len; i++) {
if (reg1[i].checked) {
return true;
} else {
alert('please select the medium');
b1 = true;
}
}
}
if (a1 == true && b1 == true) {
return true;
}
}
</script>
Myform is:
<form name="f1" action="s.php" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
像這樣
代替onclick使用onsubmit並分配功能onload
window.onload=function() { document.getElementsByName("f1")[0].onsubmit=function() { var chk = document.getElementsByName('subject[]'),chkOk=false; for (var i = 0, n=chk.length; i < n; i++) { if (chk[i].checked) { chkOk = true; break; } } console.log(chkOk) if (!chkOk) { alert('please select the subject'); chk[0].focus(); // focus the first return false; } var reg = document.getElementsByName('regional[]'),regOk=false; for (var i = 0, n=reg.length; i < n; i++) { if (reg[i].checked) { regOk = true; break; } } if (!regOk) { alert('please select the medium'); reg[0].focus(); // focus the first return false; } return true; // allow submit } }
<form name="f1" action="s.php" method="post" onsubmit="return check()"> Subject <input type='checkbox' name='subject[]' value='science'>science <input type='checkbox' name='subject[]' value='maths'>maths<br/> Medium <input type='checkbox' name='regional[]' value='Hindi'>Hindi <input type='checkbox' name='regional[]' value='english'>english<br/> <input type="submit" name="land" class="butt" value="SUBMIT"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.