jQuery set radio button

前端 未结 12 1993
执笔经年
执笔经年 2020-12-02 11:12

I am trying to set a radio button. I want set it by using the value or the id.

This is what I\'ve tried.

$(\'input:radio[name=cols]\'+\" #\"+newcol).         


        
相关标签:
12条回答
  • 2020-12-02 11:14

    The chosen answer works in this case.

    But the question was about finding the element based on radiogroup and dynamic id, and the answer can also leave the displayed radio button unaffected.

    This line does selects exactly what was asked for while showing the change on screen as well.

    $('input:radio[name=cols][id='+ newcol +']').click();
    
    0 讨论(0)
  • 2020-12-02 11:18

    In my case, radio button value is fetched from database and then set into the form. Following code works for me.

    $("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);
    
    0 讨论(0)
  • 2020-12-02 11:21

    Try this:

    $("#" + newcol).attr("checked", "checked");
    

    I've had issues with attr("checked", true), so I tend to use the above instead.

    Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

    0 讨论(0)
  • 2020-12-02 11:22

    Using .filter() also works, and is flexible for id, value, name:

    $('input[name="cols"]').filter("[value='Site']").attr('checked', true);

    (seen on this blog)

    0 讨论(0)
  • 2020-12-02 11:24

    In your selector you seem to be attempting to fetch some nested element of your radio button with a given id. If you want to check a radio button, you should select this radio button in the selector and not something else:

    $('input:radio[name="cols"]').attr('checked', 'checked');
    

    This assumes that you have the following radio button in your markup:

    <input type="radio" name="cols" value="1" />
    

    If your radio button had an id:

    <input type="radio" name="cols" value="1" id="myradio" />
    

    you could directly use an id selector:

    $('#myradio').attr('checked', 'checked');
    
    0 讨论(0)
  • 2020-12-02 11:25

    You can simply use:

    $("input[name='cols']").click();
    
    0 讨论(0)
提交回复
热议问题