Set selected radio from radio group with a value

后端 未结 10 577
深忆病人
深忆病人 2020-12-04 06:04

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=myg         


        
10条回答
  •  天命终不由人
    2020-12-04 06:34

    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 then you will be able to add checked property / attribute to one of the radio button in that radio buttons group.

    Code To Remove Checked Attribute from all radio buttons of one radio button group -

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

提交回复
热议问题