JS 如何获取radio或者checkbox选中后的值

时间:2023-12-09 15:10:49

废话不多说,直接上代码:

代码:

<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS 如何获取radio或者checkbox选中后的值</title>
</head> <body>
<p>单选框</p>
<input type="radio" name="sex" value="man" id="man" checked onclick="inputChecked()">
<label for="man">男</label>
<input type="radio" name="sex" value="female" id="female" onclick="inputChecked()">
<label for="female">女</label>
<p>多选框</p>
<input type="checkbox" name="fruits" value="apple" id="apple" checked onclick="inputChecked()">
<label for="apple">苹果</label>
<input type="checkbox" name="fruits" value="orange" id="orange" onclick="inputChecked()">
<label for="orange">橙子</label>
<script>
inputChecked(); function inputChecked() {
var inputSelect = document.getElementsByTagName('input');
var obj = {
radio: [],
checkbox: []
},
value = '';
for (var i = 0, len = inputSelect.length; i < len; i++) {
if (inputSelect[i].checked && inputSelect[i].type === 'radio') {
obj.radio.push(inputSelect[i].value);
value += '单选框:' + inputSelect[i].value + '\n';
}
if (inputSelect[i].checked && inputSelect[i].type === 'checkbox') {
obj.checkbox.push(inputSelect[i].value);
value += '多选框:' + inputSelect[i].value + '\n';
}
}
alert(value);
return obj;
}
</script>
</body> </html>