05-使用jQuery操作input的value值
表单控件是我们的重中之重 , 因为一旦牵扯到数据交互, 离不开form 表单的使用 , 比如用户的注册登录功能等 ,
$(selector).val() // 设置值和获取值
select 标签是下拉列表
后面跟 option
看如下HTML结构 :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <from action=""> <input type="radio" name="sex" value="112"/>男 <!--设置checked属性表示选中当前选项--> <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="timeespan" 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"/> </from> </body> </html>
页面展示效果:

操作表单控件代码如下:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
//一 , 获取值
// 1. 获取单选框被选中的value值
console.log($("input[type=radio]:checked").val());
// 2 . 复选框被选中的value , 获取的是第一个被选中的值
console.log($("input[type=checkbox]:checked").val());
// 3. 下拉类表被选中的值
var obj = $("#timespan option:selected");
// 获取被选中的值
var time = obj.val();
console.log(time)
// 获取文本
var time_text = obj.text();
console.log("val:"+time_text+" text"+time_text);
// 4 . 获取文本框的value值
console.log($("input[type=text]").val());
//二 , 设置值
// 1. 设置单选按钮和多选按钮被选中项
$("input[type=radio]").val(["112"]);
$("input[type=checkbox]").val(["a","b"]);
//2.设置下拉列表框的选中值, 必须使用select
/*因为option只能设置单个值 , 当给select标签设置multiple
那么 我们设置多个值 , 就没有办法了 , 但是使用select设置单个值和多个值都可以*/
$("select").val(["3","2"])
// 3. 设置文本框的value值
$("input[type=text]").val("试试就试试")
})
</script>

浙公网安备 33010602011771号