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

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

设置单选下拉框的选中值

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

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

1)option中没有value属性:

<select id="single">
  <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 id="single">
  <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 id="multiple" 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" name="hobby" value="check1" checked="checked"/>多选1
<input type="checkbox" name="hobby" value="check2"/>多选2
<input type="checkbox" name="hobby" value="check3"/>多选3
<input type="checkbox" name="hobby" value="check4"/>多选4
<input type="checkbox" name="hobby" 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" name="sport" value="soccer"/>足球
<input type="radio" name="sport" value="volleyball"/>排球
<input type="radio" name="sport" value="baseball"/>棒球
<input type="radio" name="sport" value="badminton"/>羽毛球
<input type="radio" name="sport" value="pingpong"/>乒乓球
$("#btn4").click(function () {
  //【方法1】
  $("input[type=radio][name=sport]").val(["volleyball"]);
  //【方法2】
  $("input[type=radio][name=sport]:eq(1)").prop("checked", true);
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。