html-Select

2017-03-11  本文已影响0人  Yepku

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态添加option</title>
</head>
<body>
<select id="mySel">
<option value="1">option-1</option>
<option value="2">option-2</option>
<option value="3">option-3</option>
</select>

新增列表项值:<input type="text" id="val"/>
内容:<input type="text" id="txt"/>
<input type='button' value='添加' onclick="inserItem()"/>

<script type="text/javascript">
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);//获取文本
}

/*

  1. 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 " ); //修改所选择中的项

  2. jQuery way:
    $(document).on("change","#mySel",function(){
    alert('value:'+$(this).val());//获取value
    alert('text:'+$(this).find("option:selected").text());//获取选中文本
    });
    $("#mySel").append("<option value='n+1'>第N+1项</option>"); //添加一个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() //为所有选项的个数
*/
</script>
</body>
</html>

上一篇下一篇

猜你喜欢

热点阅读