如何在 jQuery 中预选单选按钮

How to pre-select a radio button in jQuery

我想预选以下集合中的第一个单选按钮:

HTML

<input type="radio" value="0" name="serviceNoteType[1]">
<input type="radio" value="1" name="serviceNoteType[1]">

jQuery

var i = 1; // for sake of this example
$('[name="serviceNoteType\['+ i +'\]"]').prop('checked', true);

结果是第二个单选按钮被选中,我想选择第一个。如何定位第一个单选按钮?

名称需要不同。您的选择器将只检查最后呈现的那个名称的元素。

$('[name="serviceNoteType\['+ i +'\]"]:first-child').prop('checked', true);

未经测试,因此语法可能略有偏差,但应该能让您大致了解。

您可以将 .first() 添加到您的选择器中:

var i = 1; // for sake of this example
$('[name="serviceNoteType\['+ i +'\]"]').first().prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" value="0" name="serviceNoteType[1]">
<input type="radio" value="1" name="serviceNoteType[1]">

更短的形式。试试这个:

$("input:radio:first").attr('checked', true);