How to check a radio button with jQuery?

2018-12-31 12:23发布

I try to check a radio button with jQuery. Here's my code:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

And the JavaScript:

jQuery("#radio_1").attr('checked', true);

Doesn't work:

jQuery("input[value='1']").attr('checked', true);

Doesn't work:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work:

Do you have another idea? What am I missing?

27条回答
素衣白纱
2楼-- · 2018-12-31 13:14

Get value:

$("[name='type'][checked]").attr("value");

Set value:

$(this).attr({"checked":true}).prop({"checked":true});

Radio Button click add attr checked:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});
查看更多
梦寄多情
3楼-- · 2018-12-31 13:14

Try this

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == '1')
        {
          // do something
        }
        else if($(this).val() == '2')
        {
          // do something
        }
        else if($(this).val() == '3')
        {
          // do something
        }
    });
});
查看更多
时光乱了年华
4楼-- · 2018-12-31 13:16

You have to do

jQuery("#radio_1").attr('checked', 'checked');

That's the HTML attribute

查看更多
不流泪的眼
5楼-- · 2018-12-31 13:16
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});
查看更多
像晚风撩人
6楼-- · 2018-12-31 13:16

attr accepts two strings.

The correct way is:

jQuery("#radio_1").attr('checked', 'true');
查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 13:17

Try This:

$("input[name=type]").val(['1']);

http://jsfiddle.net/nwo706xw/

查看更多
登录 后发表回答