jquery获取radio的值

发布时间 2023-12-20 16:53:15作者: csjoz11

要获取选中的 radio 按钮的值,可以使用 jQuery 中的 :checked 选择器和 val() 方法。

  以下是一个例子:

html

<input type="radio" name="fruit" value="apple" id="appleRadio"> <label for="appleRadio">Apple</label>
<input type="radio" name="fruit" value="banana" id="bananaRadio"> <label for="bananaRadio">Banana</label>
<input type="radio" name="fruit" value="orange" id="orangeRadio"> <label for="orangeRadio">Orange</label>
<button id="submitButton">Submit</button>

js

$(document).ready(function() {
$('#submitButton').click(function() {
const selectedValue = $('input[name="fruit"]:checked').val();
console.log(selectedValue);
});
});

  在上面的例子中,当点击按钮时,会获取选中的 radio 按钮的值,并通过 console.log() 方法输出。$('input[name="fruit"]:checked') 选择器用于选中 name 属性为 "fruit" 且被选中的 radio 按钮。val() 方法用于获取选中的 radio 按钮的值。

  注意:如果没有任何一个 radio 按钮被选中,$('input[name="fruit"]:checked').val() 返回 undefined。因此在使用前需要先进行判断是否有选中的 radio 按钮。