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!
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");
}
})
if( !$(':radio:checked').length){
alert('Please select one radio');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With