Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any radio or checkbox is selected

How would I use jQuery to determine if a checkbox or radio button is checked or not?

Here is my HTML:

<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

<span id="check1">check</span>

<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>

<span id="check2">check</span>

Here is some psuedo JavaScript:

$("#check1").click(function(){
    if(any radio is selected){
       alert("Please select one radio");
    }
})

$("#check2").click(function(){
    if(any checkbox is selected){
       alert("Please select minimum one checkbox");
    }
})

It is possible in jQuery?

Live example on jsfiddle: http://jsfiddle.net/BghzK/ Thanks for help!

like image 745
Peter Agger Avatar asked Dec 04 '22 05:12

Peter Agger


2 Answers

You can make use of the :checked pseudoselector in your selector expression. Combine this with .length to see how many have been returned. In this case we get all selected radio buttons and see if length is zero, indicating that none have been selected.

http://jsfiddle.net/mrtsherman/BghzK/2/

$("#check1").click(function(){
    if($('input[type=radio]:checked').length == 0){
       alert("Please select one radio");
    }
})

$("#check2").click(function(){
    if($('input[type=checkbox]:checked').length == 0){
       alert("Please select minimum one checkbox");
    }
})

​
like image 89
mrtsherman Avatar answered Dec 18 '22 23:12

mrtsherman


if( !$(':radio:checked').length){
    alert('Please select one radio');
}
like image 35
charlietfl Avatar answered Dec 18 '22 22:12

charlietfl