[英]Checking to see if atleast one item has been selected in a checkbox list using javascript
我想讓我的代碼檢查是否在復選框列表中選中了一個或多個復選框。 如果沒有選中復選框,那么我想要一個window.alert彈出“請選擇至少一個興趣”。 目前所做的一切都是提醒,即使您選中了一個方框也沒有檢查過任何內容。
我的代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Web Site Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function confirmSubmit(){
if(document.forms[0].interests.checked) {
{window.alert("Thank you");}
} else {
{window.alert("Select at least one preference");
}
return false;}
return true;
}
</script>
</head>
<body>
<h1>Web Site Registration Form</h1>
<h2>Personal Information</h2>
<form action="FormProcessor.html" method="get"
enctype="application/x-www-form-urlencoded" onsubmit="return confirmSubmit()">
<p>Select areas of interest (select at least one)</p>
<p><input type="checkbox" name="interests"
value="entertainment">Entertainment<br />
<input type="checkbox" name="interests"
value="business">Business<br />
<input type="checkbox" name="interests"
value="music">Music<br />
<input type="checkbox" name="interests"
value="shopping">Shopping<br />
<input type="checkbox" name="interests"
value="travel">Travel</p>
<p><input type="submit"></p>
</form>
</body>
</html>
注意:標題中的額外代碼用於提交輸入到顯示已提交內容的頁面的所有數據。 這是我的第一篇文章,請隨時告訴我其他信息可能會有什么幫助。 謝謝!
在表單下方添加腳本標記,您可以使用this
標記將表單傳遞給您的回調。 使用querySelector
:checked
以在表單內搜索已檢查的輸入。
<script type="text/javascript">
function confirmSubmit(form){
if(form.querySelector(":checked")) {
window.alert("Thank you");
return true;
} else {
window.alert("Select at least one preference");
return false;
}
}
</script>
您可以通過更新onclick
監聽器將表單傳遞給您的回叫;
<form action="FormProcessor.html" method="get"
enctype="application/x-www-form-urlencoded"
onsubmit="return confirmSubmit(this)">
這是小提琴。
使用jQuery,您可以這樣做:
function confirmSubmit(){
$('input').each(function(index, item) {
if(item.checked){
return true;
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.