前端 —— JavaScript 基础篇 23 --- js获取input 、radio、checkbox、select 的值

    技术2025-10-10  5

    js:如何获取input的值

    <lable>input的值:</lable> <input type="text" id="userName" placeholder="请输入用户名" /> <script type="text/javascript"> var userInput = document.getElementById('userName'); console.log(userInput.value;) </script>

     

    JS:如何获取 radio 的值

    <lable>radio的值:</lable> <input type="radio" name="gender" class="radio" value="男" />男 <input type="radio" name="gender" class="radio" value="女" />女 <script type="text/javascript"> var gender = document.getElementsByName('gender'); for(var i = 0;i < gender.length; i++){ if(gender[i].checked == true){ console.log(gender[i].value) } } </script>

     

    js:如何获取 checkbox 的值

    <lable>checkbox的值</lable> <input type="checkbox" name="hobby" value="旅游" class="ckbox" />旅游 <input type="checkbox" name="hobby" value="宅家" class="ckbox"/>宅家 <input type="checkbox" name="hobby" value="运动" class="ckbox"/>运动 <input type="checkbox" name="hobby" value="看书" class="ckbox"/>看书 <script type="text/javascript"> var hobby = document.getElementsByName('hobby'); var check_arr = []; for (var i = 0; i < hobby.length; i++) { if(hobby[i].checked){ check_arr.push(hobby[i].value) ; } } </script>

    JS:如何获取 select 的值

    <lable>select的值</lable> <select id="select"> <option value="-1" >请选择</option> <option value="A" url="http://www.baidu.com">第一个option</option> <option value="B" url="http://www.qq.com">第二个option</option> </select> <script type="text/javascript"> var select = document.getElementById('select'); var index = select.selectedIndex;//获取被选中项的index值 console.log(select.options[index].text); console.log(select.options[index].value); console.log(select.options[index].url); </script>

     

    我的文章都是学习过程中的总结,如果发现错误,欢迎留言指出,我及时更正。

     

     

     

    Processed: 0.016, SQL: 9