option-1
option-2
option-3
新增列表项值:
内容:
function inserItem(){
var val = document.getElementById("val").value;
var txt = document.getElementById("txt").value;
var sel = document.getElementById("mySel");
var option = new Option(txt, val);
sel.options.add(option);
}
function getvalue(obj) {
var m=obj.options[obj.selectedIndex].value
var n=obj.options[obj.selectedIndex].text
alert(m);//获取value
alert(n);//获取文本
}
/*
Native way:
var mySel = document.getElementById("mySel");
mySel.options.length=0; //动态删除select中的所有options
mySel.options.remove(indx); //动态删除select中的某一项option:
mySel.options.add(new Option(text,value)); //动态添加select中的项option
var m = mySel.options[indx].value(or .text) //获取文本/value
if (mySel.selectedIndex > - 1 ) { //检测是否有选中
mySel.options[mySel.selectedIndex] = null ; //删除被选中的项
mySel.options[mySel.selectedIndex] = new Option( " 你好 " , " hello " ); //修改所选择中的项
jQuery way:
$(document).on("change","#mySel",function(){
alert('value:'+$(this).val());//获取value
alert('text:'+$(this).find("option:selected").text());//获取选中文本
});
$("#mySel").append("第N+1项"); //添加一个option
$("#mySel option:selected").text(); //获取选中的内容
$("#mySel option:selected").attr("id"); //获取选中的的option的id值
$('#mySel option:selected').remove(); //添除选中项
$("#mySel option:eq(1)").remove(); // 删除第2个元素
$('#mySel option[value=5]').remove();
$('#mySel option:first').val(); // 获取第1个option的值
$("#mySel").attr('value' , $('#test option').eq($('#test option').length - 1).val());
$("#mySel option:selected").attr("data-xx", "---");
$("#mySel").find("option:selected").atrr("自定义属性")
var selectId = $('#mySel>option:selected');
$(":selected").length //为选择的个数,
$("select option").size() //为所有选项的个数
*/