给定一个值,使用循环,将符合此值的option选中,分别使用jQuery与原生js实现
// 原始数据被覆盖之前,受理渠道值
var beforeVal = $("#ccsChanelTypeTbl option:selected").val();
// 当前勾选的受理渠道值
var currentVal = $("#cb_" + policy).attr("channelType");
// 原生js 回显受理渠道
for (var i = 0; i < document.getElementById("ccsChanelTypeTbl").options.length; i++) {
if (currentVal == document.getElementById("ccsChanelTypeTbl").options[i].value) {
document.getElementById("ccsChanelTypeTbl").options[i].selected = true;
}
}
// 使用jQuery实现 回显受理渠道
$("#ccsChanelTypeTbl option").each(function () {
if ($(this).val() == currentVal) {
$(this).attr("selected", true);
}
});
可以看到使用jQuery会更简洁一点
一些其他语法
<select id="selector">
<option value="1">选项一option>
<option value="2">选项二option>
<option value="3">选项三option>
<option value="4">选项四option>
select>
获取当前选中项的text和value
$("#selector").find("option:selected").text();
$("#selector").find("option:selected").val();
获取当前选中的索引值(从0开始)
$("#selector").get(0).selectedIndex;
获取第一项(最小)和最后一项(最大)的text
$("#selector option:last").text();
$("#selector option:first").text();
更改和设置选中状态
改变select的选中,执行该语句后将第0个改为被选中状态,这里eq(i),i为索引值
$("#selector").each(function(){
$(this).find("option").eq(0).prop("selected",true)
});
为select添加事件,当选择其中一项时触发事件
$('#selector').change(function (e) {
alert(1243);
});
设置select索引值为1的项选中
$("#selector").get(0).selectedIndex = 1;
设置select的value值为’1’的项选中
$("#selector option[value='1']").prop("selected", true);
添加/删除select的option项:
为select追加一个option(下拉项),在末尾添加
$("#selector").append("");
为select追加一个option(下拉项),在起始添加
$("#selector").prepend("");
删除select中最后一个option
$("#selector option:last").remove();
删除select中value='3’的option
$("#selector option[value='3']").remove();
使select不可点击与解除不可点击
$("#activityId").change(function() {
// 不是未选 且 选择的不是 [1000000001],工单类型就只能为 [210001]
var activity = $("#activityId").find("option:selected").val();
if ( activity != "" && activity != "1000000001") {
$("#workorderType option[value='210001']").prop("selected", true);
$("#workorderType").attr("disabled", "disabled");
} else {
$("#workorderType").removeAttr("disabled");
}
});