1.单选按钮 type="radio"
同一组的单选按钮name属性值必须一致,因为单选的排他性依靠的就是这个name
<!-- 下面两个的name属性都是game 他们只能选出其中的一个 -->
<input type="radio" name="game" value="LOL">英雄联盟
<input type="radio" name="game" value="ra2">红色警戒2
<!-- 下面两个的name属性都是game 他们只能选出其中的一个 -->
<input type="radio" name="sex" value="man">男
<input type="radio" name="sex" value="women">女
设置默认选中 checked
<input type="radio" name="sex" value="man" checked>男
<input type="radio" name="sex" value="women">女
JS获取当前选中单选框的值
var radios = document.querySelectorAll('input[name=sex]')
function getVal(){
radios.forEach(item => {
if(item.checked){
console.log(item.value)
}
})
}
2.复选按钮 type="checkbox"
请为同一组的按钮设定相同的name
<input type="checkbox" name="game" value="LOL">英雄联盟
<input type="checkbox" name="game" value="ra2">红色警戒2
<input type="checkbox" name="game" value="kof">拳皇
设置默认选中 checked
<input type="checkbox" name="game" value="LOL" checked>英雄联盟
<input type="checkbox" name="game" value="ra2" checked>红色警戒2
<input type="checkbox" name="game" value="kof">拳皇
JS获取当前选中复选框的值
var checks = document.querySelectorAll('input[name=game]')
function getVal(){
var arr = []
checks.forEach(item => {
if(item.checked) {
arr.push(item.value)
}
})
console.log(arr)
}
3.下拉菜单
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
设置默认选中 selected
<select name="cars" id="car">
<option value="volvo">Volvo</option>
<option value="saab" selected>Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
JS获取下拉菜单的值,哪个option被选中,他的value值就是select的value值
var select = document.querySelector('#car')
console.log(select.value)
4.表单默认选中的注意点
<input type="radio" name="sex" value="man" checked>男
<input type="radio" name="sex" value="women">女
<input type="checkbox" name="game" value="LOL" checked>英雄联盟
<input type="checkbox" name="game" value="ra2" checked>红色警戒2
<input type="checkbox" name="game" value="kof">拳皇
实际上标签内的checked/selected属性只是页面渲染的时候初始化内存而已,真正生效的是内存中对应的值
以单选按钮的性别为例,默认为"男",此时你手动选中切换为"女",Dom结构如下
<input type="radio" name="sex" value="man" checked>男
<input type="radio" name="sex" value="women">女
这说明,Dom里面标签展示的checked属性不会随着操作而改变,它永远都是页面加载时的样子。这也意味着,要判断一个单选/多选框被选中,查看Dom标签展示的相关属性是不准确的,它永远是页面初始化时候的样子(即中看不中用)
想要获取表单的选中状态,只能使用点语法(不推荐getAttribute)
document.querySelector('input').checked;