js radio单选框
在网页开发中,单选框(radio button)是一种常用的元素,用于让用户在几个选项中选择一个。在JavaScript中,我们可以通过操作单选框来实现许多有趣的功能。本文将详细介绍如何在JS中使用单选框。
1. 创建单选框
要在网页中创建一个单选框,可以使用<input>
标签并将其type
属性设置为”radio”。每个单选框还应该有一个唯一的name
属性,以便在同一组单选框中进行区分。
<input type="radio" name="color" value="red"> 红色
<input type="radio" name="color" value="blue"> 蓝色
<input type="radio" name="color" value="green"> 绿色
在上面的示例中,我们创建了一个颜色选择的单选框组。用户只能选择其中的一个选项。
2. 获取选择的值
要获取用户选择的单选框的值,可以通过JavaScript使用document.querySelector()
方法来选中对应的单选框,并读取它的value
属性。
<input type="button" value="获取选择的颜色" onclick="getSelectedColor()">
<script>
function getSelectedColor() {
var color = document.querySelector('input[name="color"]:checked').value;
alert("您选择了:" + color);
}
</script>
在这个示例中,我们通过点击一个按钮来获取用户选择的颜色,并用弹窗显示出来。
3. 设置默认选中项
有时候,我们需要在页面加载时设置某个单选框为默认选中状态。这可以通过在<input>
标签中添加checked
属性来实现。
<input type="radio" name="fruit" value="apple" checked> 苹果
<input type="radio" name="fruit" value="banana"> 香蕉
<input type="radio" name="fruit" value="orange"> 橙子
在这个示例中,苹果单选框会在页面加载时被默认选中。
4. 动态操作单选框
通过JavaScript,我们可以动态地操作单选框,例如:通过点击按钮来改变选中状态、禁用某个选项等。
<input type="radio" name="gender" value="male"> 男性
<input type="radio" name="gender" value="female"> 女性
<input type="button" value="禁用女性选项" onclick="disableFemale()">
<script>
function disableFemale() {
document.querySelector('input[value="female"]').disabled = true;
}
</script>
在这个示例中,点击按钮后,女性选项将被禁用,用户无法再选择。
5. 实际应用示例
下面是一个实际的应用示例:一个网页上有两组单选框,用户可以选择不同的选项来展示不同的内容。
<input type="radio" name="category" value="news"> 新闻
<input type="radio" name="category" value="sport"> 体育
<input type="radio" name="type" value="video"> 视频
<input type="radio" name="type" value="article"> 文章
<div id="content"></div>
<script>
document.querySelectorAll('input[type="radio"]').forEach(function(input) {
input.addEventListener('change', function() {
var category = document.querySelector('input[name="category"]:checked').value;
var type = document.querySelector('input[name="type"]:checked').value;
var content = category + " - " + type;
document.getElementById("content").innerText = content;
});
});
</script>
在这个示例中,用户可以通过选择不同的类别和类型来显示不同的内容。当用户改变选择时,内容会自动更新。
结语
单选框是网页开发中常用的交互元素,我们可以通过JavaScript来操作和控制这些单选框,实现更加丰富和动态的功能。