05-使用jQuery操作input的value值
表单控件是我们的重中之重,因为一旦牵扯到数据交互离不开form表单的使用,比如用户的注册登陆功能等
那么通过上节知识点我们了解到,我们在使用jquery方法操作表单控件的方法:
$(selector).val() //设置值获取值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action=""> <input type="radio" name="sex" value="112" />男 <!-- 设置cheked属性表示选中当前选项 --> <input type="radio" name="sex" value="11" checked="" />女 <input type="radio" name="sex" value="11" />gay <input type="checkbox" value="a" checked=""/>吃饭 <input type="checkbox" value="b" />睡觉 <input type="checkbox" value="c" checked=""/>打豆豆 <!-- 下拉列表 option标签内设置selected属性 表示选中当前 --> <select name="timespan" id="timespan" class="Wdate" > <option value="1">8:00-8:30</option> <option value="2" selected="">8:30-9:00</option> <option value="3">9:00-9:30</option> </select> <input type="text" name="" id="" value="111" /> </form> </body> </html>
<script src="jquery.js"></script> <script> $(function(){ // 1, 获取值 //1.1获取单选框被选中的value值 console.log($('input[type=radio]:checked').val()) //1.2复选框被选中的value, 获取的是第一个被选中的值 console.log($('input[type=checkbox]:checked').val()) //1.3下拉列表被选中的值 var obj = $("#timespan option:selected"); var time = obj.val() console.log(time) //获取文本 var time_text = obj.text(); console.log('val:'+time+" text"+time_text); //1.4 获取文本框的值 console.log($("input[type=text]").val())//获取文本框中的值 //2,设置值 //2.1 设置单选按钮和多选按钮被选中项 $("input[type=radio]").val(['112']); $('input[type=checkbox]').val([a, b]); //2.2设置下拉列表框的选中值,必须使用select /* 因为option只能设置单个值,当给select标签设置multiple.那么我们设置多个值,就没有办法了,只是使用select设置单个值和多个值都可以 */ $('select').val(['3', '2']) //2.3 设置文本框value值 $('input[type=text]').val('试试就试试') }) </script>

浙公网安备 33010602011771号