Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  44] [ 3]  / answers: 1 / hits: 25580  / 12 Years ago, tue, august 7, 2012, 12:00:00

I know that may have a few similar questions @stackoverflow, but I didnt found any solution to my problem yet :s



<?php
while($rowVideo = mysql_fetch_array($ResultQueryVideo))
{
?>
<input type=checkbox name = checkbox-1[] class=checkbox value =<?php echo $rowVideo['idVideo'] ?> /> <?php....some code...


This results a few checkbox's, the same number as idVideo..thats the point.



Now, before the submit, I need to be sure that at least one checkbox is checked. But i was not sucesseful :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;
}
}


Extra details:
form name = form1



Can you guide me a litle ?
Thanks



EDIT:



function isCountCheck(){
if($(input[type=checkbox]:checked).length > 0)
{
return true;
}
else
{
alert('Invalid');
return false;
}
}


But still not working..even that alert is shown..


More From » checkbox

 Answers
68

The main problem is that you're not using the i index within the loop to reference the individual checkboxes, and you've got a . just before the [ which is a syntax error. So change:



if(document.form1.[checkbox-1[]].checked) chkCnt++;


To:



if(document.form1[checkbox-1[]][i].checked) chkCnt++;


But you can neaten up the function somewhat as follows:



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;
}


Demo: http://jsfiddle.net/nnnnnn/ZjK3w/1/



Or just loop through all inputs in the form, checking the type (and/or the name) of each one:



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;
}


Demo: http://jsfiddle.net/nnnnnn/ZjK3w/2/


[#83809] Sunday, August 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elijahm

Total Points: 674
Total Questions: 124
Total Answers: 79

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
elijahm questions
Thu, Dec 9, 21, 00:00, 3 Years ago
Mon, Aug 9, 21, 00:00, 3 Years ago
Fri, Mar 19, 21, 00:00, 3 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;