jQuery set radio button

前端 未结 12 1994
执笔经年
执笔经年 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:27

    Your selector looks for the descendant of a input:radio[name=cols] element that has the id of newcol (well the value of that variable).

    Try this instead (since you're selecting by ID anyway):

    $('#' + newcol).prop('checked',true);
    

    Here is a demo: http://jsfiddle.net/jasper/n8CdM/1/

    Also, as of jQuery 1.6 the perferred method of altering a property is .prop(): http://api.jquery.com/prop

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

    I found the answer here:
    https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery

    Basically, if you want to check one radio button, you MUST pass the value as an array:

    $('input:radio[name=cols]').val(['Site']);
    $('input:radio[name=rows]').val(['Site']);
    
    0 讨论(0)
  • 2020-12-02 11:36

    Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

    $('#'+newcol).prop('checked', true);
    
    0 讨论(0)
  • 2020-12-02 11:37

    Since newcol is the ID of the radio button, You can simply use it as below.

    $("#"+newcol).attr('checked',true);
    
    0 讨论(0)
  • 2020-12-02 11:38

    You can try the following code:

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

    This will set the attribute checked for the radio columns and value as specified.

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

    Combining previous answers:

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