1、设置value为pxx的项选中
$(".selector").val("pxx");
2、设置text为pxx的项选中
$(".selector").find("option[text='pxx']").attr("selected",true);
这里有一个中括号的用法,中括号里的等号的前面是属性名称,不用加引号。很多时候,中括号的运用可以使得逻辑变得很简单。
3、获取当前选中项的value
$(".selector").val();
4、获取当前选中项的text
$(".selector").find("option:selected").text();
这里用到了冒号,掌握它的用法并举一反三也会让代码变得简洁。
5、获取当前选中项的索引值:
$('select#sel').get(0).selectedIndex;
6、获取当前option的最大索引值:
$('select#sel option:last').attr("index")
7、获取DropdownList的长度:
$('select#sel')[0].options.length;
或者
$('select#sel').get(0).options.length;
8、设置第一个option为选中值:
$('select#sel option:first').attr('selected','true')
或者
$('select#sel')[0].selectedIndex = 0;
9、设置最后一个option为选中值:
$('select#sel option:last).attr('selected','true')
10、根据索引值设置任意一个option为选中值:
$('select#sel')[0].selectedIndex =索引值;索引值=0,1,2....
11、设置Value=4 的option为选中值:
$('select#sel').attr('value','4');
或者
$("select#sel option[value='4']").attr('selected', 'true');
12、 删除Value=3的option:
$("select#sel option[value='3']").remove();
13、 删除第几个option:
$(" select#sel option ").eq(索引值).remove();索引值=0,1,2....
如删除第3个Radio:
$(" select#sel option ").eq(2).remove();
14、 删除第一个option:
$(" select#sel option ").eq(0).remove();
或者
$("select#sel option:first").remove();
15、 删除最后一个option:
$("select#sel option:last").remove();
16、 删除dropdownlist:
$("select#sel").remove();
17、在select后面添加一个option:
$("select#sel").append("f");
18、在select前面添加一个option:
$("select#sel").prepend("0");
19、 遍历option:
$(' select#sel option ').each(function (index, domEle) {
//写入代码
});
很多时候用到select的级联,即第二个select的值随着第一个select选中的值变化。这在jquery中是非常简单的。
如:$(".selector1").change(function(){
// 先清空第二个
$(".selector2").empty();
// 实际的应用中,这里的option一般都是用循环生成多个了
var option = $("<option>").val(1).text("pxx");
$(".selector2").append(option);
});