在jQuery中,当它们都具有相同的名称时,如何获得单选按钮的值? [英] In jQuery, how do I get the value of a radio button when they all have the same name?
问题描述
这是我的代码:
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
这是JS:
$(function(){
$("#submit").click(function(){
alert($('input[name=q12_3]').val());
});
});
这是 JSFIDDLE !每次我点击按钮它都会返回1.为什么?任何人都可以帮助我吗?
Here is JSFIDDLE! Every time I click button it returns 1. Why? Can anyone help me?
推荐答案
在你的代码中,jQuery只查找名为<$ c $的输入的第一个实例c> q12_3 ,在这种情况下的值为 1
。您想要一个名称 q12_3
的输入 :已选中
。
In your code, jQuery just looks for the first instance of an input with name q12_3
, which in this case has a value of 1
. You want an input with name q12_3
that is :checked
.
$("#submit").click(() => {
const val = $('input[name=q12_3]:checked').val();
alert(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
请注意,上述代码不与使用 .is(:checked)
。 jQuery的 是()
函数返回一个布尔值(真或假)而不是(一)元素。
Note that the above code is not the same as using .is(":checked")
. jQuery's is()
function returns a boolean (true or false) and not (an) element(s).
因为这个答案一直受到很多关注,我还将包含一个vanilla JavaScript代码段。
Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.
document.querySelector("#submit").addEventListener("click", () => {
const val = document.querySelector("input[name=q12_3]:checked").value;
alert(val);
});
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
这篇关于在jQuery中,当它们都具有相同的名称时,如何获得单选按钮的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!