41

I am trying to check radio. Neither the following works:

[edit]

$('selector').attr('checked','checked');
$('selector').attr('checked',true);

The two alert() in the following code show "1" and "a", respectively. My expectation is the second alert() showing "b".

Opera does check the second radio box in its browser, but its element inspector, dragonfly, shows that the DOM is not changed.

[end edit]

I had read the FAQ before I posted this question:

http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_check.2Funcheck_a_checkbox_input_or_radio_button.3F

Helps will be much appreciated!

TIA

The xhtml page and code follows:

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Weird Behavior</title>
<script type="text/javascript" src="scripts/jquery.js"/>
<script type="text/javascript">
function clickme(){
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"][checked]').val());
};
</script>
</head>
<body>
    <form action="">
        <fieldset>
            <legend>Why check is not switched?</legend>
            <input type="radio" name="myname" value="a" id="a" checked="checked"/>A
            <input type="radio" name="myname" value="b" id="b"/>B
        </fieldset>
    </form>
    <p>
    <button type="button" onclick="clickme()">click me</button>
    </p>
</body>
</html>
Masao Liu
  • 749
  • 2
  • 7
  • 16

7 Answers7

162
 $('.checkbox').attr('checked',true);

will not work with from jQuery 1.6.

Instead use

$('.checkbox').prop('checked',true);
$('.checkbox').prop('checked',false);

Full explanation / examples and demo can be found in the jQuery API Documentation https://api.jquery.com/attr/

Rohan
  • 578
  • 8
  • 12
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
18

With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

$('button').click(function() {
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"]:checked').val());
});

http://jsfiddle.net/uL545/1/

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Yes, using jQuery to add the event listener is better, but your explanation is wrong. The function is found, and your demo still echos `a` (it should echo `b`). – Felix Kling Mar 11 '11 at 08:53
  • @Squeegy: Pseudo selector `:checked` does do its job. Thank you very much! While I have got the code working , I still do not understand the behavior of radio check box. It appears that `checked` attribute behaves differently from others. As shown in the following example, the second alert() correctly display `b`, but the first alert() pops up `a`, which is quite beyond my expectation. Would you please explain more about this for me? `$('#b').attr('checked',true); $('#b').addClass('test'); alert($('input[name="myname"][checked]').val()); alert($('[class="test"]').val());` – Masao Liu Mar 12 '11 at 04:11
  • @Masao Liu: Actually, I tried to explain it in my answer. Did you understand it? What is unclear? – Felix Kling Mar 12 '11 at 22:40
  • Form elements are special cases. When their values change, the DOM does not update. Using the attribute selector `[someattr]` checks the actual DOM and not the current value. Check this example out: http://jsfiddle.net/Squeegy/h8T97/ If you change the text field value and click the button you will notice the HTML is unchanged, but the value is different than the attribute says it should be. So with all form fields you need to be aware that their current state may be different then the DOM would say. You need to ask the element for it's value rather than parsing attributes. – Alex Wayne Mar 13 '11 at 01:08
  • @Felix Kling, @Squeegy: I did read Felix Kling's explanation repeatedly but failed to get your points because adding `$('#a').removeAttr('checked');` did not solve my original problem, either. Thanks to Squeegy's latest explanation, now I guess I know the subtle behavior of form elements -- changing their values do not alter DOM content. Many thanks again! – Masao Liu Mar 13 '11 at 03:11
  • @fizer-khan should be accepted answer? `$('.checkbox').prop('checked',true);` – Simon Hutchison Aug 28 '17 at 02:58
13
$('.checkbox').prop('checked',true); 
$('.checkbox').prop('checked',false);

... works perfectly with jquery1.9.1

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
trace
  • 361
  • 1
  • 4
  • 9
11

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

KingRider
  • 2,140
  • 25
  • 23
2
$("input:radio").attr("checked",true); //for all radio inputs

or

$("your id or class here").attr("checked",true); //for unique radios

equally the same works for ("checked","checked")

Ed Fryed
  • 2,160
  • 16
  • 14
1

I don't think you can call

$.attr('checked',true);

because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!

RubyFanatic
  • 2,241
  • 3
  • 22
  • 35
1

It works, but

$('input[name="myname"][checked]').val()

will return the value of the first element with attribute checked. And the a radio button still has this attribute (and it comes before the b button). Selecting b does not remove the checked attribute from a.

You can use jQuery's :checked:

$('input[name="myname"]:checked').val()

DEMO


Further notes:

  • Using $('b').attr('checked',true); is enough.
  • As others mentioned, don't use inline event handlers, use jQuery to add the event handler.
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143