count of selected radio buttons in jquery

2019-04-06 02:09发布

问题:

suppose I have groups of radio buttons like so:

<label><input type="radio" value="1" name="rdQueen" /> Scaramouche</label> <br />
<label><input type="radio" value="1" name="rdQueen" /> Will you do the</label> <br />
<label><input type="radio" value="1" name="rdQueen" /> Fandango</label> <br />

... sometime later in the page ...

<label><input type="radio" value="1" name="rdFruit" /> Mango</label> <br />
<label><input type="radio" value="1" name="rdFruit" /> Kiwi</label> <br />
<label><input type="radio" value="1" name="rdFruit" /> Potato</label> <br />

All I want to do is make sure atleast one of them from both group has been selected.. so I need to count the radiobuttons that have been checked, in this case it'll be 2.

Only, I am not sure how to do that. help please!

回答1:

To check for only those specific groups:

$(':radio[name="rdQueen"]:checked, :radio[name="rdFruit"]:checked').length;

Example: http://jsfiddle.net/AlienWebguy/HzfKq/



回答2:

You could do:

 var numberOfCheckedRadio = $('input:radio:checked').length
 //this gives you the total of checked radio buttons on the page


回答3:

Use the checked-selector[docs] to get the ones that are checked, and the length[docs] property to find out how many there were.

alert( $('input:radio:checked').length );