36

I have this HTML:

<input type="radio" name="test" id="test" value="1"><br>
<input type="radio" name="test" id="test" value="2"><br>
<input type="radio" name="test" id="test" value="3"><br>

<input type="button" onclick="CreateJobDo">

When the page loads, none of them will be checked. I want to use jQuery to check if one of the radio buttons is checked when the button is pressed.

I have this:

function CreateJobDo(){
    if ($("input[@name=test]:checked").val() == 'undefined') {

        // go on with script

    } else {

        // NOTHING IS CHECKED
    }
}

But this does not work. How to get it working?

CDspace
  • 2,639
  • 18
  • 30
  • 36
Mbrouwer88
  • 2,182
  • 4
  • 25
  • 38
  • 9
    IDs **MUST** be unique. – j08691 Mar 20 '13 at 17:28
  • @LightnessRacesinOrbit He wants to check if any of his radio boxes are checked, and currently his test statement isn't working. – RestingRobot Mar 20 '13 at 17:33
  • Well, maybe you have an old version of the question, because your quote isn't in it? "When the page loads, none of them will be checked. I to use Jquery to check if one of the radio buttons is checked?" - assuming he "wants to use JQuery". – RestingRobot Mar 20 '13 at 17:48
  • Sorry, stupid context :) I have a button under it which has to check if one of the radio buttons are checked. – Mbrouwer88 Mar 20 '13 at 18:42
  • This asks about radio buttons, and the duplicate question asks about checkboxes. I (now) know both use the same `:checked` syntax, but it was confusing to confirm it. They should have been left separate questions. – goodeye Nov 09 '18 at 02:49

5 Answers5

79

First of all, have only one id="test"

Secondly, try this:

if ($('[name="test"]').is(':checked'))
Ray
  • 894
  • 1
  • 6
  • 23
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
50

try this

if($('input:radio:checked').length > 0){
// go on with script
 }else{
    // NOTHING IS CHECKED
 }
Mohamed Habib
  • 883
  • 1
  • 8
  • 18
17

Something like this:

 $("input[name=test]").is(":checked");

Using the jQuery is() function should work.

RestingRobot
  • 2,938
  • 1
  • 23
  • 36
11
if($("input:radio[name=test]").is(":checked")){
  //Code to append goes here
}
talha2k
  • 24,937
  • 4
  • 62
  • 81
3
  $('#submit_button').click(function() {
    if (!$("input[@name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });
Ray
  • 894
  • 1
  • 6
  • 23