如何在加载时通过jQuery选择单选按钮

How to select a radio button through jQuery on load?

本文关键字:jQuery 选择 单选按钮 加载      更新时间:2024-04-15

$("#1").find("Radio1").prop('checked', true);
$("#2").find("Radio1").prop('checked', true);
<div id="1" cvalue='false'>
  Are you a student  ?
  <br> <input type="radio" name="RadioB1" id="Radio1" value="1">
  <label for="Radio1">Yes</label><br>
  <input type="radio" name="RadioB1" id="Radio2" value="2">
  <label for="Radio2">No</label>
</div>
<br/>
<div id="2"  cvalue='false' >
  Do you study in a university ?
  <br>
  <input type="radio" name="RadioB1" id="Radio3" class="ui-state-default ui-corner-all" value="1">
  <label for="Radio1">Yes</label><br>
  <input type="radio" name="RadioB1" id="Radio4" class="ui-state-default ui-corner-all" value="2">
  <label for="Radio2">No</label>
</div>

演示

首先,两个单选类按钮的名称应该保持不同,以便从两个div中进行选择。

第二,你正在寻找标签并设置其道具,相反,你应该找到输入单选按钮为:

HTML:

<div id="1"  cvalue='false'>
        Are you a student  ?
         <br> <input type="radio" name="RadioB1" id="Radio1" value="1">
          <label for="Radio1">Yes</label><br>
          <input type="radio" name="RadioB1" id="Radio2" value="2">
          <label for="Radio2">No</label>


</div>
<br/>
<div id="2"  cvalue='false' >
   Do you study in a university ?
        <br>
          <input type="radio" name="RadioB1" id="Radio3" class="ui-state-default ui-corner-all" value="1">
          <label for="Radio1">Yes</label><br>
          <input type="radio" name="RadioB1" id="Radio4" class="ui-state-default ui-corner-all" value="2">
          <label for="Radio2">No</label>

</div>

JS:

$('#1').find('input[name=RadioB1]').filter('#Radio1').prop('checked', true);
$('#2').find('input[name=RadioB2]').filter('#Radio3').prop('checked', true);

请参阅此演示

我想知道为什么要使用javascript来执行此操作?你可以像这样使用纯html

<div id="1" cvalue='false'>
  Are you a student  ?
  <br> <input type="radio" name="RadioB2" id="Radio1" value="1" checked="checked">
  <label for="Radio1">Yes</label><br>
  <input type="radio" name="RadioB2" id="Radio2" value="2">
  <label for="Radio2">No</label>
</div>
<br/>
<div id="2"  cvalue='false' >
  Do you study in a university ?
  <br>
  <input type="radio" name="RadioB1" id="Radio3" class="ui-state-default ui-corner-all" value="1" checked="checked">
  <label for="Radio1">Yes</label><br>
  <input type="radio" name="RadioB1" id="Radio4" class="ui-state-default ui-corner-all" value="2">
  <label for="Radio2">No</label>
</div>

注意: 您只需要使用checked="checked"并使用不同的name为每个问题选择多个