如何使用 JavaScript 禁用单选按钮?
单选按钮是一种输入类型,以选项的形式接收输入。用户将从多个选项中选择一个值。在多个可能的选项中,只能选择一个。
在本文中,我们将探讨如何禁用单选按钮以及如何在需要时重新启用它。我们将了解单选按钮的内部工作原理以及如何在需要时禁用它们。
大多数情况下,单选按钮仅在某些情况下作为确认的一部分显示给用户。不需要时,我们可以禁用它们,以免用户选择选项。
方法
在这种方法中,我们将使用 HTML 提供的 `disabled` 属性。此属性允许您禁用任何 HTML 元素。这是一个布尔值属性,只有两个值,即 `true` 或 `false`。使用 `disabled` 时,它会禁用该特定的 HTML 元素。`disabled` 的默认值为 `false`。
示例
在下面的示例中,我们将一个字符串与正则表达式进行比较,如果字符串匹配则返回其索引。如果不匹配,则返回 -1。
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- CSS code required for the page -->
<style>
#submit {
width: 30%;
margin: 20px;
height: 40px;
border-radius: 20px;
color: black;
font-size: 1rem;
font-weight: bold;
border: 1px solid black;
cursor: pointer;
}
#submit:hover {
background-color: grey;
color: rgb(0, 0, 0);
}
</style>
</head>
<body>
<div>
<h1 style="color: green;">Welcome To Tutorials Point</h1>
<h2>Do you like sports ?</h2>
<div class="question1">
<label><input name="sport" type="radio" id="yes" value="yes"/> Yes</label>
<label><input name="sport" type="radio" id="no" value="no" onchange="check()" /> No</label>
</div>
<h2>
If No, Choose your favourite sport.
</h2>
<div class="question2">
<label><input type="radio" name="sports" id="cricket" value="Cricket" />Cricket</label>
<label><input type="radio" name="sports" id="football" value="Football" />Football</label>
<label><input type="radio" name="sports" id="basketball" value="Basket Ball" />Basket Ball</label>
<label><input type="radio" name="sports" id="others" value="Others" /> Others</label>
</div>
<button id="submit" onclick="message()">
Submit
</button>
</div>
<script>
// This function will check if the user has
// selected any option from the question 1
function check() {
if (document.getElementById('no').checked) {
document.getElementById('cricket').disabled = true;
document.getElementById('football').disabled = true;
document.getElementById('basketball').disabled = true;
document.getElementById('others').disabled = true;
}
}
// This function will give the message after
// the user clicks on the submit button.
function message() {
if (document.getElementById('yes').checked) {
if (document.getElementById('cricket').checked) {
alert("You like Cricket.");
}
else if
(document.getElementById('football').checked) {
alert("You like Football.");
}
else if
(document.getElementById('basketball').checked) {
alert("You like Basket Ball.");
}
else if
(document.getElementById('others').checked) {
alert("You like Other sports.");
}
} else {
alert("You donot like sports");
}
}
</script>
</body>
</html>输出
对于问题“你喜欢运动吗?”,如果您选择“是”,则单选按钮不会被禁用;但如果您选择“否”,则单选按钮会被禁用。

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP