[英]Javascript count checked checkbox
我知道@stackoverflow可能有一些類似的問題,但是我還沒有找到解決我問題的方法:
<?php
while($rowVideo = mysql_fetch_array($ResultQueryVideo))
{
?>
<input type="checkbox" name = "checkbox-1[]" class="checkbox" value ="<?php echo $rowVideo['idVideo'] ?>" /> <?php....some code...
這將產生幾個復選框,與idVideo..number相同。
現在,在提交之前,我需要確保至少選中了一個復選框。 但我沒有成功:x
function isCountCheck (helperMsg) {
var chkCnt = 0;
var Frm = document.forms[0];
var dLen = Frm.length - 1;
for (i=0;i<=dLen;i++) {
if(document.form1.["checkbox-1[]"].checked) chkCnt++;
}
if (chkCnt>0) {
return true;
} else {
alert(helperMsg);
return false;
}
}
額外的詳細信息:表單名稱=“ form1”
你能指導我一小撮嗎? 謝謝
編輯:
function isCountCheck(){
if($("input[type=checkbox]:checked").length > 0)
{
return true;
}
else
{
alert('Invalid');
return false;
}
}
但是仍然無法正常工作。即使顯示了該警報。
主要問題是您沒有在循環內使用i
索引來引用各個復選框,而您卻擁有一個.
[
之前是語法錯誤。 所以改變:
if(document.form1.["checkbox-1[]"].checked) chkCnt++;
至:
if(document.form1["checkbox-1[]"][i].checked) chkCnt++;
但是您可以按如下方式整理功能:
function isCountCheck(helperMsg) {
var i, dLen = document.form1["checkbox-1[]"].length;
// if the length property is undefined there is only one checkbox
if (typeof dLen === "undefined") {
if (document.form1["checkbox-1[]"].checked) return true;
}
else {
for (i = 0; i < dLen; i++) {
if (document.form1["checkbox-1[]"][i].checked) return true;
}
}
alert(helperMsg);
return false;
}
演示: http : //jsfiddle.net/nnnnnn/ZjK3w/1/
或者只是循環訪問表單中的所有輸入,檢查每個輸入的類型(和/或名稱):
function isCountCheck(helperMsg) {
var i, len, inputs = document.form1.getElementsByTagName("input");
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox"
&& inputs[i].checked)
return true;
}
alert(helperMsg);
return false;
}
var form = document.forms[0]; // your form element (whatever)
var checkedElms = form.querySelectorAll(':checked').length;
不需要jQuery。 支持到IE8。 如果需要,可將polyfill用於較舊的瀏覽器。
使用jQuery:
function isCountCheck(helperMsg){
if($("input[type=checkbox]:checked").length > 0)
return true;
alert(helperMsg);
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.