37

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?

5
  • 9
    IDs MUST be unique. Commented Mar 20, 2013 at 17:28
  • @LightnessRacesinOrbit He wants to check if any of his radio boxes are checked, and currently his test statement isn't working. Commented Mar 20, 2013 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". Commented Mar 20, 2013 at 17:48
  • Sorry, stupid context :) I have a button under it which has to check if one of the radio buttons are checked. Commented Mar 20, 2013 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. Commented Nov 9, 2018 at 2:49

5 Answers 5

79

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

Secondly, try this:

if ($('[name="test"]').is(':checked'))
Sign up to request clarification or add additional context in comments.

3 Comments

Isnt the name="test" a typo? i believe the right onw is ($('[id="test"]').is(':checked'))
Don't overthink it. And You'd never do $('[id="test"]') you'd do $('#test')
I had the same situation and this answer was the one that help me. I gave my vote. Thank you.
49

try this

if($('input:radio:checked').length > 0){
// go on with script
 }else{
    // NOTHING IS CHECKED
 }

2 Comments

imo you can safely remove the > 0 part 'cause positive integers are true
It works, but it doesn't read as well as $("input:radio").is(':checked').
17

Something like this:

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

Using the jQuery is() function should work.

1 Comment

checked works for both radios and checkboxes
11
if($("input:radio[name=test]").is(":checked")){
  //Code to append goes here
}

Comments

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!');
    }
  });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.