jQuery设置和获取select、checkbox、radio的选中值方法

select、checkbox、radio是很常用的表单控件,熟练掌握操作它们的方法,会加快我们的开发速度。

设置单选下拉框的选中值

如果option中没有value属性,那可以通过text设置选中项;

如果option中有value属性,那必须通过value设置选中项。

1)option中没有value属性:

<select> <option>选择1号</option> <option>选择2号</option> <option>选择3号</option> </select> $("#btn1").click(function() { //【方法1】 $("#single").val("选择3号"); //【方法2】 $("#single").val(["选择3号"]); //【方法3】 $("#single option:eq(2)").prop("selected", true); });

2)option中有value属性:

<select> <option value="1">选择1号</option> <option value="2">选择2号</option> <option value="3">选择3号</option> </select> $("#btn1").click(function() { //【方法1】 //通过val("选择3号")设置选中项无效 $("#single").val("选择3号"); //通过val("3")设置选中项有效 $("#single").val("3"); //【方法2】 $("#single option:eq(2)").prop("selected", true); });

设置多选下拉框的选中值

多选下拉框默认的选中值是“选择1号”和“选择3号”。如果用val()的方式设置选中值是“选择2号”和“选择4号”,那只有“选择2号”和“选择4号”会被选中;如果用prop(“selected”, true)的方式设置选中值是“选择2号”和“选择4号”,那默认的“选择1号”和“选择3号”以及“选择2号”和“选择4号”都会被选中。

<select multiple="multiple"> <option selected="selected">选择1号</option> <option>选择2号</option> <option selected="selected">选择3号</option> <option>选择4号</option> <option>选择5号</option> </select> $("#btn2").click(function () { //【方法1】 $("#multiple").val(["选择2号", "选择4号"]); //【方法2】 $("#multiple option:eq(1)").prop("selected", true); $("#multiple option:eq(3)").prop("selected", true); });

设置多选框的选中值

多选框默认的选中值是“check1”。如果用val()的方式设置选中值是“check2”和“check4”,那只有
“check2”和“check4”会被选中;如果用prop(“selected”, true)的方式设置选中值是“check2”和“check4”,那默认的“check1”以及“check2”和“check4”都会被选中。

<input type="checkbox" value="check1" checked="checked"/>多选1 <input type="checkbox" value="check2"/>多选2 <input type="checkbox" value="check3"/>多选3 <input type="checkbox" value="check4"/>多选4 <input type="checkbox" value="check5"/>多选5 $("#btn3").click(function () { //【方法1】 $("input[type=checkbox][name=hobby]").val(["check2","check4"]); //【方法2】 $("input[type=checkbox][name=hobby]:eq(1)").prop("checked", true); $("input[type=checkbox][name=hobby]:eq(3)").prop("checked", true); });

设置单选框的选中值

设置单选框的选中值不能用val(“volleyball”),必须用val([“volleyball”])。

<input type="radio" value="soccer"/>足球 <input type="radio" value="volleyball"/>排球 <input type="radio" value="baseball"/>棒球 <input type="radio" value="badminton"/>羽毛球 <input type="radio" value="pingpong"/>乒乓球 $("#btn4").click(function () { //【方法1】 $("input[type=radio][name=sport]").val(["volleyball"]); //【方法2】 $("input[type=radio][name=sport]:eq(1)").prop("checked", true); });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwjgjf.html