Radio Buttons "Checked" Attribute Not Working
Asked Answered
R

15

88

The radio button does not show up as checked by default. I started off without a default choice doing some very simple js validation and it wasn't working. So I opted to just use default values until I figured that out and discovered that something weird is going on.

The markup is valid and I've tried in FF, Safari and Chrome. Nothing works.

I think it's a conflict with the jQuery library because the problem goes away when I remove the call script.

<label>Do you want to accept American Express?</label> Yes
<input id="amex" style="width: 20px;" type='radio' name='Contact0_AmericanExpress' value='1' /> No
<input style="width: 20px;" type='radio' name='Contact0_AmericanExpress' class='check' value='0' checked="checked" />
Revolutionize answered 31/8, 2010 at 6:57 Comment(2)
What exactly is your problem here? I copied your HTML into an empty file, and the "No" button is checked. This is IE8, FF and Opera.Margaret
see the answer (kind of workaround though) belowDody
G
107

If you have multiple of the same name with the checked attribute it will take the last checked radio on the page.

<form>
    <label>Do you want to accept American Express?</label>
    Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
    maybe<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  checked="checked" />  
    No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>
Guzel answered 5/4, 2011 at 18:34 Comment(5)
It'll actually check the last radio within the <form>. You can have several checked inputs with the same name, as long as they belong to different forms.Lionhearted
This was the issue in my case. The page had two divs, only one of which was displayed at a time. Both had a radio button group with the same name. In my instance, both had the checked attribute, but the browser seemed to be choosing the one from the hidden div (the latter one in the HTML) as the one to use for showing the selected radio button.Acquaintance
@BrunoLange This was my problem. I was rendering multiple instances of the same HTML on the page - which consisted of two radio buttons not enclosed within a form tag, with one radio button having the checked property. I had to wrap them in a <form> tag for each instance to have the default radio button checked.Idaidae
I needed to have the radio buttons and their uniquely named groups wrapped in their own form tags.Quintin
this solved my problem, elements had same name while they are iterated and created dynamically!!!Remediless
S
52

Radio inputs must be inside of a form for 'checked' to work.

Sandman answered 30/1, 2017 at 19:21 Comment(10)
Putting the input of type radio inside a form (it was div before) solves my problem! I'm curious what's the reason for this?Yablon
Same here. I really don't know why a form tag is needed to get the check work reliably... o.oSymbolize
I don't think this is necessary but using a form element will allow the naming to be 'scoped' I guess so the checked attribute will work.Idona
@CharisTheo, It is, in fact, necessary. Try for yourself.Sandman
@MichaelSeltenreich I did indeed and I have fixed this problem with changing the name of the radio buttons without including them in a form elementIdona
Your solution will fail on some major browsersSandman
I think this is sometimes related to a scoping issue. In my case, the issue was because I had multiple radios with the same name and value within the same document. Adding the <form> tags around each set seems to fix the issue, but changing the names of the various sets also works.Sparling
Bizzare I had other sets where "checked" worked in the same page, but indeed for THIS set to work the whole page had to be in a form. Shrug.Canady
Accidentally found that answer and using form solved my issue!Rosamariarosamond
This still applies in 2024! How odd.Toneytong
S
40

This might be it:

Is there a bug with radio buttons in jQuery 1.9.1?

In short: Don't use attr() but prop() for checking radio buttons. God I hate JS...

Servitor answered 10/9, 2013 at 10:2 Comment(2)
This may not have answered the OP's question, but it answered mineGermander
just found out the same issue yesterday.Olimpiaolin
G
11

The ultimate JavaScript workaround to this annoying issue -

Simply wrap the jQuery command in a setTimeout. The interval can be extremely small, I use 10 milliseconds and it seems to be working great. The delay is so small that it is virtually undetectable to the end users.

setTimeout(function(){
  $("#radio-element").attr('checked','checked');
},10);

This will also work with

  • $("#radio-element").trigger('click');
  • $("#radio-element").attr('checked',true);
  • $("#radio-element").attr('checked',ANYTHING_THAT_IS_NOT_FALSE);

Hacky...hacky...hacky...hacky... Yes I know... hence this is a workaround....

Gymnasiarch answered 24/5, 2012 at 13:6 Comment(2)
It seems that you are setting the attribute 'Checked' on all #radio-elements in your first example.Omentum
As it is an id selector, there should be only 1 matching elementProserpina
O
5

Hey I was also facing similar problem, in an ajax generated page.. I took generated source using Webdeveloper pluggin in FF, and checked all the inputs in the form and found out that there was another checkbox inside a hidden div(display:none) with same ID, Once I changed the id of second checkbox, it started working.. You can also try that.. and let me know the result.. cheers

Overmatter answered 19/10, 2011 at 6:10 Comment(0)
S
3

Just copied your code into: http://jsfiddle.net/fY4F9/

No is checked by default. Do you have any javascript running that would effect the radio box?

Shows answered 31/8, 2010 at 7:2 Comment(4)
I know, it's crazy right? No I don't have any scripts going that address radio buttons. Just some validation on text fields and a slider script. I'm going thru it right now just to make sure though..Revolutionize
Found the culprit but I don't know exactly what in that script is causing the problemRevolutionize
Thanks Ben but it's definitely the script. When disabled I can see the buttons checked by default.Revolutionize
Actually I think it's a conflict with the JQuery libraryRevolutionize
M
3

The jQuery documentation provides a detailed explanation for checked property vs attribute.

Accordingly, here is another way to retrieve selected radio button value

var accepted = $('input[name="Contact0_AmericanExpress"]:checked').val();
Mandi answered 8/7, 2016 at 17:24 Comment(0)
Y
3

I could repro this by setting the name of input tag the same for two groups of input like below:

<body>
  <div>
      <div>
        <h3>Header1</h3>
      </div>
      <div>
          <input type="radio" name="gender" id="male_1" value="male"> Male<br>
          <input type="radio" name="gender" id="female_1" value="female" checked="checked"> Female<br>
          <input type="submit" value="Submit">
      </div>
  </div>


  <div>
      <div>
        <h3>Header2</h3>
      </div>
      <div>
          <input type="radio" name="gender" id="male_2" value="male"> Male<br>
          <input type="radio" name="gender" id="female_2" value="female" checked="checked"> Female<br>
          <input type="submit" value="Submit">
      </div>
  </div>
</body>

(To see this running, click here)

The following two solutions both fix the problem:

  1. Use different names for the inputs in the second group
  2. Use form tag instead of div tag for one of the groups (can't really figure out the real reason why this would solve the problem. Would love to hear some opinions on this!)
Yablon answered 15/5, 2019 at 22:45 Comment(0)
O
1

hi I think if you put id attribute for the second input and give it a unique id value it will work

<label>Do you want to accept American Express?</label>
Yes<input id="amex" style="width: 20px;" type='radio' name='Contact0_AmericanExpress'   value='1'/>  
No<input style="width: 20px;" id="amex0" type='radio' name='Contact0_AmericanExpress' class='check' value='0' checked="checked"/>
Obelia answered 6/1, 2012 at 22:22 Comment(0)
C
1

**Radio button aria-checked: true or false one at a time**

$('input:radio[name=anynameofinput]').change(function() {
            if (this.value === 'value1') {
                $("#id1").attr("aria-checked","true");
                $("#id2").attr("aria-checked","false");
            }
            else if (this.value === 'value2') {;
                $("#id2").attr("aria-checked","true");
                $("#id1").attr("aria-checked","false");
            }
   });
Course answered 21/2, 2019 at 19:17 Comment(0)
H
1

also try this way

$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

Hame answered 4/3, 2020 at 7:31 Comment(0)
C
0

Your code is right, try to debug your JQuery script to find the issue! If you're using FF you can install an extension to debug JS (and JQuery) it's called FireBug.

Compensatory answered 31/8, 2010 at 13:28 Comment(0)
V
-2

You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)

Try this:

<form>
  <label>Do you want to accept American Express?</label>
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>
Voyageur answered 31/8, 2010 at 7:6 Comment(3)
thats's up to Jordan's doc type. regardless of that it'll still work in a xhtml doctype; it won't validate however.Shows
I changed it just for kicks but I know that isn't the problem. Validation is nice but it won't solve this one.Revolutionize
@CFP Actually, double or single quotes are allowed in standards compliant XHTML (transitional, strict, HTML5, etc). See: dev.w3.org/html5/html-author/#double-quote-attrSordid
B
-2

just add checked attribute to each radio that you want to have default checked

try this :

<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked/>
Befuddle answered 26/1, 2014 at 14:22 Comment(0)
F
-2

Replace checked="checked" with checked={true}. Or you could even shorten it to just checked.

This is because the expected value type of the checked prop is a boolean. not a string.

Flats answered 12/4, 2020 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.