在JavaScript中操作单选按钮(radio button)使其被选中,可以通过修改其checked
属性来实现。以下是具体的方法和示例:
checked
属性checked
属性<form id="myForm">
<input type="radio" id="option1" name="options" value="1">
<label for="option1">选项 1</label><br>
<input type="radio" id="option2" name="options" value="2">
<label for="option2">选项 2</label><br>
<input type="radio" id="option3" name="options" value="3">
<label for="option3">选项 3</label><br>
<button type="button" onclick="selectRadio('option2')">选中选项 2</button>
</form>
function selectRadio(radioId) {
// 方法一:通过ID选择元素并设置checked属性
var radio = document.getElementById(radioId);
if (radio) {
radio.checked = true;
}
// 方法二:通过表单元素集合选择(假设表单ID为myForm)
/*
var form = document.getElementById('myForm');
var radios = form.elements['options'];
for (var i = 0; i < radios.length; i++) {
if (radios[i].id === radioId) {
radios[i].checked = true;
break;
}
}
*/
}
document.getElementById
获取到指定的单选按钮元素,然后设置其checked
属性为true
,即可选中该单选按钮。checked
属性。这种方法适用于当有多个单选按钮且它们属于同一个表单时。name
属性,这样才能确保它们在同一组内互斥。getElementById
是最直接的选择方式,但如果有多个操作或动态生成的元素,可能需要使用更灵活的选择器如querySelector
。通过上述方法,你可以轻松地使用JavaScript来控制单选按钮的选中状态,从而增强页面的交互性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云