我尝试用jQuery检查单选按钮。这是我的代码:

<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>

JavaScript:

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

不工作:

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

不工作:

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

不工作:

你还有别的主意吗?我错过了什么?


当前回答

我使用这个代码:

我为英语感到抱歉。

var $j = jQuery.noConflict(); $j(function() { // add handler $j('#radio-1, #radio-2').click(function(){ // find all checked and cancel checked $j('input:radio:checked').prop('checked', false); // this radio add cheked $j(this).prop('checked', true); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset class="section"> <legend>Radio buttons</legend> <label> <input type="radio" id="radio-1" checked> Option one is this and that&mdash;be sure to include why it's great </label> <br> <label> <input type="radio" id="radio-2"> Option two can be something else </label> </fieldset>

其他回答

最短的

radio_1.checked

checkBtn。Onclick = e=> { console.log (radio_1。检查); } 选择第一个单选并单击按钮 <!——问题html——> < >形式 < div id =“类型”> <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 > > < /形式 <!——测试html——> <按钮id = " checkBtn " >查看> < /按钮

这里是Jsfiddle代码片段

试试这个:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});

试试这个。

在本例中,我以它的输入名称和值为目标

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

很高兴知道:在多词值的情况下,它也会工作,因为撇号。

试试这个

$(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
        }
    });
});

此外,你可以检查元素是否被选中:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

你可以检查未检查的元素:

$('.myCheckbox').attr('checked',true) //Standards way

你也可以这样取消勾选:

$('.myCheckbox').removeAttr('checked')

您可以检查单选按钮:

对于jQuery等于或高于(>=)1.6的版本,请使用:

$("#radio_1").prop("checked", true);

对于(<)1.6之前的版本,使用:

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