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
.(在您的代码中,jQuery只查找名为q12_3
的输入的第一个实例,在这种情况下,其值为1
。)
You want an input with name q12_3
that is :checked
.(您想要一个名为q12_3
的输入: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")
.(注意,以上代码是不一样的使用.is(":checked")
)
jQuery's is()
function returns a boolean (true or false) and not (an) element(s).(jQuery的is()
函数返回一个布尔值(true或false)而不是(a)元素。)
Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.(因为这个答案一直受到很多关注,我还会包含一个vanilla 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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…