<html !DOCTYPE>
<head>
<title>表单元素值获取</title>
</head>
<body>
<div>
<h1>下拉列表</h1>
<select id="weekday">
<option>---</option>
<option>星期一</option>
<option>星期二</option>
<option>星期三</option>
<option>星期四</option>
<option>星期五</option>
</select>
</div>
<div>
<h1>多选框</h1>
<input type="checkbox" name="hobby" value="swimming"><span>swimming</span>
<input type="checkbox" name="hobby" value="singing"><span>singing</span>
<input type="checkbox" name="hobby" value="drawing"><span>drawing</span>
<input type="checkbox" name="hobby" value="travelling"><span>travelling</span>
</div>
<div>
<h1>单选框</h1>
<input type="radio" name="sex" value="boy"><span>boy</span>
<input type="radio" name="sex" value="girl"><span>girl</span>
</div>
<div>
<input type="button" value="点击获取下拉列表的值" onclick="getSelectorValue()">
<input type="button" value="点击获取多选框的值" onclick="getCheckboxValue()">
<input type="button" value="点击获取单选框的值" onclick="getRadioValue()">
</div>
</body>
</html>
解释说明部分在注释中
<script>
//用原生JS获取
var getSelectorValue = function(){
var selector = document.getElementById("weekday");
//先获取到整个下拉列表,在获取到被选中元素的索引,最后得到值
var value = selector.options[selector.selectedIndex].value;
console.log(value);
}
var getCheckboxValue = function(){
var checkbox = document.getElementsByName("hobby");
console.log(checkbox);//是一个节点列表
checkbox.forEach(element => {
if(element.checked){
//获取到被选中的元素节点
console.log(element);
//获取节点中的value属性
console.log(element.value);
}
});
}
var getRadioValue = function(){
var radio = document.getElementsByName("sex");
console.log(radio);//是一个节点列表
radio.forEach(element => {
if(element.checked){
//获取到被选中的元素节点
console.log(element);
//获取节点中的value属性
console.log(element.value);
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//用JQuery获取
var getSelectorValue = function(){
var value = $("#weekday").val();
console.log(value);
}
var getCheckboxValue = function(){
//获取到所有被选中的列表
var checkbox = $("input[name='hobby']:checked");
for(var i=0; i<checkbox.length; i++){
console.log(checkbox[i].value);
}
}
var getRadioValue = function(){
//因为是单选可以直接获取到被选中的值
var value = $("input[name='sex']:checked").val();
console.log(value);
}
</script>
Practice Makes Perfect
14 天前