Check if any radio or checkbox is selected

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

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 are 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"); } }) 

Maybe in jQuery?

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

+4
source share
6 answers

You can use the :checked pseudo-selector in a selector expression. Combine this with .length to see how many have been returned. In this case, we will get all the selected radio buttons and see if the length is zero, indicating that none of them are 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"); } })​ 
+6
source
 if( !$(':radio:checked').length){ alert('Please select one radio'); } 
+4
source

You will need to use (": checked") with the selector. Sample code below:

  $(function() { $("#check1").click(function(){ if(!($("input[name='sex']").is(":checked"))){ alert("Please select one radio"); } }) $("#check2").click(function(){ if(!($("input[name='vehicle']").is(":checked"))){ alert("Please select minimum one checkbox"); } }) }); 
+3
source

use jquery Validation plugin made automatically. For the radio button, you just need to make the required element in the form.

+2
source
 var rdo = $('input[name="group"]:checked'); var boxes = $('input[type="checkbox"]:checked'); if(rdo.length == 0) alert("Please select one radio"); if(boxes.length == 0) alert("Please select minimum one checkbox"); 
+1
source

you can try this way this simple

  var chkvalue = $('input[name="sex"]:checked').val(); if(chkvalue =="") { alert("Please checked the radio button"); return; } 
+1
source

Source: https://habr.com/ru/post/1398526/


All Articles