Set selected radio from radio group with a value

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

    Try this:

    $('input:radio[name="mygroup"][value="5"]').attr('checked',true);
    

    JS Fiddle demo.

    0 讨论(0)
  • 2020-12-04 06:46

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

    JS fiddle Demo

    0 讨论(0)
  • 2020-12-04 06:48

    There is a better way of checking radios and checkbox; you have to pass an array of values to the val method instead of a raw value

    Note: If you simply pass the value by itself (without being inside an array), that will result in all values of "mygroup" being set to the value.

    $("input[name=mygroup]").val([5]);
    

    Here is the jQuery doc that explains how it works: http://api.jquery.com/val/#val-value

    And .val([...]) also works with form elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>.

    The inputs and the options having a value that matches one of the elements of the array will be checked or selected, while those having a value that don't match one of the elements of the array will be unchecked or unselected

    Fiddle demonstrating this working: https://jsfiddle.net/92nekvp3/

    0 讨论(0)
  • 2020-12-04 06:50

    Or you can just write value attribute to it:

    $(':radio[value=<yourvalue>]').attr('checked',true);
    

    This works for me.

    0 讨论(0)
提交回复
热议问题