用JS和JQuery分别获取表单元素的值(select,checkbox,radio)
废话不多说直接上代码
HTML部分
<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>
用JavaScript的方法
解释说明部分在注释中
<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>
用JQuery的方法
<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
相关推荐
zhanghaibing00 2020-06-28
MaureenChen 2020-05-25
风飞飘扬 2014-06-24
lbPro0 2019-11-03
donghongbz 2019-10-19
85931235 2012-01-11
yFifhting 2017-06-08
NARUTOLUOLUO 2019-07-01
攻城师 2019-06-29
HotStrong 2017-06-08
zfjdoreen 2016-04-13
89367741 2016-03-30
shiyiboke 2016-03-29
SinhaengHhjian 2016-01-25
89453862 2015-10-10
SinhaengHhjian 2015-07-31