基于值的单选按钮选择
问题描述:
如何选择一个单选按钮,其值是唯一通过JS唯一的按钮。这似乎有点奇怪,但我需要。 Html代码如下基于值的单选按钮选择
<td class="Customer_Name"><table>
<td>
<input name="Name" tabindex="4" id="Name" type="radio" value="01">John</td>
<input name="Name" tabindex="4" id="Name" type="radio" value="02">Sam</td>
<input name="Name" tabindex="4" id="Name" type="radio" value="03">Fred</td>
<input name="Name" tabindex="4" id="Name" type="radio" value="04">Peter</td>
<td>
答
对于多个元素,您不能具有相同的id
。 id
应该是唯一的。
您可以使用querySelector
与属性值选择器。
document.querySelector('input[type="radio"][value="02"]')
document.querySelector('input[type="radio"][value="02"]').checked = true;
<td class="Customer_Name">
<table>
<td>
<input name="Name" type="radio" value="01" />John</td>
<td>
<input name="Name" type="radio" value="02" />Sam</td>
<td>
<input name="Name" type="radio" value="03" />Fred</td>
<td>
<input name="Name" type="radio" value="04" />Peter</td>
<td>
使用jQuery
$('input[type="radio"][value="02"]').prop('checked', true);
为什么所有的元素都具有相同的ID。 ID应该是唯一的一个良好的HTML结构 – bugwheels94