这是我的代码:

<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>

Here is JS:

$(function(){
    $("#submit").click(function(){      
        alert($('input[name=q12_3]').val());
    });
 });

这是JSFIDDLE美元!每次我点击按钮,它都会返回1.为什么?有谁可以帮我?

推荐答案

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>

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).


因为这个答案一直很受关注,所以我还将包括一个普通的JavaScript片段.

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相关问答推荐

jQuery从JSON创建嵌套列表

使用带有 bootstrap 验证的 Ajax 函数时出现问题

jQuery 时间 Select 器

在 CSS3 或 jQuery 中将元素的宽度从 0% 设置为 100% 动画,它和它的包装器只需要它们需要的宽度,没有预先设置的宽度

ASP .NET MVC 在每个字段级别禁用客户端验证

根据属性'data-sort'对jQuery中的div进行排序?

如何使用 jquery 更改 onclick 事件?

如何在我的 WordPress 插件中包含 CSS 和 jQuery?

如何在 jquery 中更新(附加到)href?

offsetTop 与 jQuery.offset().top

如何检测是否安装了 Flash,如果没有,显示一个隐藏的 div 通知用户?

如何使用jquery获取点击链接的href?

捕获在页面任意位置按下的 Enter 键

Bootstrap 4 文件输入

判断 JS 对象中是否存在键

如何淡出显示:inline-block

请求的资源错误中不存在Access-Control-Allow-Origin标头

如何删除集中的 contenteditable pre 周围的边框?

获取对象属性中的最小值/最大值的快速方法

如何使用 jQuery 的 form.serialize 但排除空字段