Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  23] [ 2]  / answers: 1 / hits: 38640  / 11 Years ago, tue, april 23, 2013, 12:00:00

i am new to the jquery, it is quite interesting, but i am having a little problem,
i am populating multiple checkboxes from database using foreach loop like this,



<? foreach($cities as $city) { ?>
<input type=checkbox name=city[] value=<?=$city->id?> id=city[] />
<? } ?>


i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated!
Many thanks in advance!


More From » php

 Answers
55

To find how many checkboxes are checked, you can use something like:



var checkedNum = $('input[name=city[]]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
}


Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name=city[]] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name=city[]]').filter(:checked).



Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.






References:




[#78701] Monday, April 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
dustin questions
;