js input checkbox 通过id 获取value
时间: 2023-09-10 07:11:49 浏览: 51
由于 checkbox 元素的 value 属性只在选中时才会被提交,因此可以通过 checked 属性来判断是否选中,并获取对应的 value 值。
以下是一个示例代码:
```html
<input type="checkbox" id="checkbox1" value="value1"> Checkbox 1<br>
<input type="checkbox" id="checkbox2" value="value2"> Checkbox 2<br>
<button onclick="getValue()">Get value</button>
<script>
function getValue() {
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
if (checkbox1.checked) {
console.log("Checkbox 1 is checked and its value is " + checkbox1.value);
}
if (checkbox2.checked) {
console.log("Checkbox 2 is checked and its value is " + checkbox2.value);
}
}
</script>
```
当用户勾选 Checkbox 1 时,点击 Get value 按钮,控制台输出:
```
Checkbox 1 is checked and its value is value1
```
同样,当用户勾选 Checkbox 2 时,点击 Get value 按钮,控制台输出:
```
Checkbox 2 is checked and its value is value2
```