在JavaScript中,判断单选框(Radio Button)是否被选中,可以通过检查单选框元素的checked
属性来实现。checked
属性是一个布尔值,如果单选框被选中,则值为true
;否则为false
。
以下是一个简单的示例代码,展示如何判断单选框是否被选中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check Radio Button</title>
</head>
<body>
<form id="myForm">
<input type="radio" id="option1" name="options" value="Option 1">
<label for="option1">Option 1</label><br>
<input type="radio" id="option2" name="options" value="Option 2">
<label for="option2">Option 2</label><br>
<input type="radio" id="option3" name="options" value="Option 3">
<label for="option3">Option 3</label><br>
<button type="button" onclick="checkRadio()">Check Selection</button>
</form>
<p id="result"></p>
<script src="script.js"></script>
</body>
</html>
function checkRadio() {
// 获取所有单选框
const radios = document.getElementsByName('options');
let selectedOption = null;
// 遍历单选框,检查哪个被选中
for (let i = 0; i < radios.length; i++) {
if (radios[i].checked) {
selectedOption = radios[i].value;
break;
}
}
// 显示结果
const resultElement = document.getElementById('result');
if (selectedOption) {
resultElement.textContent = `Selected option: ${selectedOption}`;
} else {
resultElement.textContent = 'No option selected';
}
}
name
属性(options
),这样它们就属于同一组。checkRadio
函数在按钮点击时被调用。document.getElementsByName('options')
获取所有名为options
的单选框。checked
属性为true
。selectedOption
并跳出循环。selectedOption
的值更新页面上的结果显示。通过这种方式,你可以轻松地在JavaScript中判断单选框是否被选中,并根据需要进行相应的处理。
领取专属 10元无门槛券
手把手带您无忧上云