jqueryradio-group

Set selected radio from radio group with a value


Why am I struggling with this?

I have a value: 5

How do I check the radio button of group "mygroup" with the value of 5?

$("input[name=mygroup]").val(5); // doesn't work?

Solution

  • With the help of the attribute selector you can select the input element with the corresponding value. Then you have to set the attribute explicitly, using .attr:

    var value = 5;
    $("input[name=mygroup][value=" + value + "]").attr('checked', 'checked');
    

    Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

    $("input[name=mygroup][value=" + value + "]").prop('checked', true);
    

    Remember you first need to remove "checked" attribute from any of radio buttons under one radio buttons group (only one button can be checked at a time); only then you will be able to add "checked" property / attribute to one of the radio buttons in that radio buttons group.

    Code to remove "checked" attribute from all radio buttons in a radio button group:

    $('[name="radioSelectionName"]').removeAttr('checked');