JS写单选框
时间: 2023-08-12 09:19:22 浏览: 36
在 HTML 中,单选框可以通过 `<input>` 元素来创建。单选框的 `type` 属性设置为 `"radio"`,并且每个单选框都需要有一个唯一的 `name` 属性来指定它们属于同一个组。下面是一个示例代码:
```
<form>
<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>
</form>
```
在上面的代码中,我们创建了三个单选框,它们属于同一个组,因为它们的 `name` 属性都被设置为 `"options"`。我们还为每个单选框指定了一个唯一的 `id`,以便将标签与单选框关联起来。每个单选框都有一个 `value` 属性,用于在提交表单时指定该选项的值。
我们还使用 `<label>` 元素为每个单选框创建了一个标签,这个标签与单选框关联在一起,以便用户可以通过点击标签来选择单选框。
通过以上代码,我们创建了一个包含三个单选框的表单,用户可以选择其中一个选项。
相关问题
js写一个单选框被单击
您可以使用 JavaScript 为单选框绑定 click 事件来实现单选框被单击后触发的事件。以下是一个简单的示例代码:
```html
<!-- HTML -->
<input type="radio" name="myRadio" value="option1" id="option1">
<label for="option1">选项1</label>
<input type="radio" name="myRadio" value="option2" id="option2">
<label for="option2">选项2</label>
```
```javascript
// JavaScript
const radio1 = document.getElementById("option1");
const radio2 = document.getElementById("option2");
radio1.addEventListener("click", function() {
console.log("选项1被单击了");
});
radio2.addEventListener("click", function() {
console.log("选项2被单击了");
});
```
在上面的示例代码中,我们为两个单选框元素分别绑定了一个 click 事件,并在事件处理函数中输出了相应的信息。当单选框被单击时,对应的事件处理函数就会被触发。需要注意的是,click 事件会在单选框被选中之前触发,如果您需要获取单选框的选中状态,可以使用 change 事件。
原生JavaScript单选框联动
当一个单选框选中时,我们可以使用JavaScript来实现与其他单选框的联动效果。以下是一个示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>单选框联动示例</title>
</head>
<body>
<h3>请选择:</h3>
<input type="radio" name="fruit" value="apple" onchange="handleFruitChange(event)">苹果
<input type="radio" name="fruit" value="orange" onchange="handleFruitChange(event)">橙子
<input type="radio" name="fruit" value="banana" onchange="handleFruitChange(event)">香蕉
<h3>你选择的是:</h3>
<p id="selectedFruit"></p>
<script>
function handleFruitChange(event) {
var selectedFruit = event.target.value;
document.getElementById("selectedFruit").textContent = selectedFruit;
}
</script>
</body>
</html>
```
在上面的代码中,我们创建了三个单选框,它们的name属性都设置为"fruit",value属性分别设置为"apple"、"orange"和"banana"。每个单选框都有一个onchange事件,在选中状态改变时会触发该事件。
在JavaScript中,我们定义了一个handleFruitChange函数,它接收一个event参数。当单选框的选中状态改变时,该函数会被调用。我们通过event.target.value来获取当前选中的值,并将其显示在id为"selectedFruit"的段落元素中。
这样,当你选择一个单选框时,选中的值就会在页面上显示出来,实现了单选框的联动效果。