html:
<select id="test"><option value="1" selected>选项一<option><option value="2">选项二<option>...<option value="n">选项N<option></select>
一、
js
1、js获取select标签选中的值
var myselect = document.getElementById("test");//获取select对象var index = myselect.selectedIndex; //获取被选中的索引var v = myselect.options[index].value; //获取被选中的值console.log("index== " + index + "value== " + v);//index== 0value== 1
2、js根据已知值设置select标签选中
var tesObj = document.getElementById("test");//方法1、设置选中选项二for(var i=0; i<tesObj.options.length; i++){if(tesObj.options[i].innerHTML == "选项二"){tesObj.options[i].selected = true;break;}}//方法2、设置选中选项二for(var i=0; i<tesObj.options.length; i++){if(tesObj.options[i].value == "2"){tesObj.options[i].selected = true;break;}}
二、jquery
1、获取第一个option的值
$('#test option:first').val();
2、获取最后一个option的值
$('#test option:last').val();
3、获取第二个option的值
$('#test option:eq(1)').val();
4、获取选中的值
$('#test').val();$('#test option:selected').val();
5、设置值为2的option为选中状态
$("#test").attr("value", "2");$("#test").prop("value", "2");
6、设置最后一个option为选中
$('#test option:last').attr('selected','selected');$("#test").attr('value' , $('#test option:last').val());$("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val());
7、获取select的长度
$('#test option').length;
8、添加一个option
$("#test").append("<option value='n+1'>第N+1项</option>");$("<option value='n+1'>第N+1项</option>").appendTo("#test");
9、添除选中项
$('#test option:selected').remove();
10、删除项选中(这里删除第一项)
$('#test option:first').remove();
11、指定值被删除
$('#test option').each(function(){if( $(this).val() == '5'){$(this).remove();}});$('#test option[value=5]').remove();
12、获取第一个Group的标签
$('#test optgroup:eq(0)').attr('label');
13、获取第二group下面第一个option的值
$('#test optgroup:eq(1) : option:eq(0)').val();
14、select 默认选中
$("#arrangeClass").find("option[value="+reim.classId+"]").prop("selected",true);