Set selected radio from radio group with a value

后端 未结 10 543
深忆病人
深忆病人 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:23

    Pure JavaScript version:

    document.querySelector('input[name="myradio"][value="5"]').checked = true;
    
    0 讨论(0)
  • 2020-12-04 06:23
    $('input[name="mygroup"]').val([5])
    
    0 讨论(0)
  • 2020-12-04 06:31
    var key = "Name_radio";
    var val = "value_radio";
    var rdo = $('*[name="' + key + '"]');
    if (rdo.attr('type') == "radio") {
     $.each(rdo, function (keyT, valT){
       if ((valT.value == $.trim(val)) && ($.trim(val) != '') && ($.trim(val) != null))
    
       {
         $('*[name="' + key + '"][value="' + (val) + '"]').prop('checked', true);
       }
      })
    }
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-12-04 06:40

    When you change attribute value like mentioned above the change event is not triggered so if needed for some reasons you can trigger it like so

    $('input[name=video_radio][value="' + r.data.video_radio + '"]')
           .prop('checked', true)
           .trigger('change');
    
    0 讨论(0)
  • 2020-12-04 06:42
    $("input[name='mygroup'][value='5']").attr("checked", true);
    
    0 讨论(0)
提交回复
热议问题