使用原型/Javascript 基于单选按钮获取表格行
我有一个 html 表,其中有一个名称和一个单选按钮,如下所示:
<table id="cars">
<thead>
<tr>
<th>Car Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="car">Ford Focus</td>
<td><input type="radio" id="selectedCar" name="selectedCar" value="8398"></td>
</tr>
<tr>
<td class="car">Lincoln Navigator</td>
<td><input type="radio" id="selectedCar" name="selectedCar" value="2994"></td>
</tr>
</tbody>
</table>
<input type="button" value="Select Car" onclick="selectCar()"></input>
我希望能够选择一个单选按钮,然后单击另一个按钮并获取单选按钮的值(这是一个唯一的 ID)以及汽车名称文本(如福特福克斯)。我应该如何编写 selectCar 方法?我尝试过一些事情,例如:
val1 = $('tr input[name=selectedCar]:checked').parent().find('#cars').html();
val1 = $("td input[name='selectedCar']:checked").parents().find('.cars').html();
val1 = $('selectedCar').checked;
但我无法获得正确的值。
我正在使用原型,但解决方案也可以是普通的 Javascript。
I have an html table that has a name and a radio button like so:
<table id="cars">
<thead>
<tr>
<th>Car Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="car">Ford Focus</td>
<td><input type="radio" id="selectedCar" name="selectedCar" value="8398"></td>
</tr>
<tr>
<td class="car">Lincoln Navigator</td>
<td><input type="radio" id="selectedCar" name="selectedCar" value="2994"></td>
</tr>
</tbody>
</table>
<input type="button" value="Select Car" onclick="selectCar()"></input>
I want to be able to select a radio button, then click another button and get the value of the radio button (which is a unique ID) as well as the car name text (like Ford Focus). How should I code the selectCar method? I've tried a few things like:
val1 = $('tr input[name=selectedCar]:checked').parent().find('#cars').html();
val1 = $("td input[name='selectedCar']:checked").parents().find('.cars').html();
val1 = $('selectedCar').checked;
but I can't get the proper values.
I'm using prototype, but the solution can be plain Javascript as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有 ID 都必须是唯一的!
您可以尝试使用此 HTML:
此后,您可以使用以下方法进行测试:(
返回
true
或false
)。或者,如果您想获取所选值,请使用 getElementsByName:
All IDs have to be unique!
You can try with this HTML:
After this, you can test using:
(returns
true
orfalse
).Or, if you want to grab the selected value, use getElementsByName: