js操作select option

1、获取选中select的value和text,html代码如下:

<select id="mySelect">
      <option value="1">one</option>
      <option value="2">two</option>
       <option value="3">three</option>
</select>

则可通过以下script代码s来获取选中的value和text

$("#mySelect").val();                                 //获取选中记录的value值 
$("#mySelect option:selected").text();         //获取选中记录的text值

2、运用new Option("文本","值")方法添加选项option

var obj = document.getElementById("mySelect");
obj.add(new Option("4","4"));

function addOption(output, value, text) {
        var option = $("<option>").val(value).text(text);
        output.append(option);
    }

3、删除所有选项option

var obj = document.getElementById("mySelect");
obj.options.length = 0;

4、删除选中选项option

var obj = document.getElementById("mySelect");
var index = obj.selectedIndex;
obj.options.remove(index);

5、修改选中选项option

var obj = document.getElementById("mySelect");
var index = obj.selectedIndex;
obj.options[index] = new Option("three",3);  //更改对应的值
obj.options[index].selected = true;  //保持选中状态

6、删除select

var obj = document.getElementById("mySelect");
obj.parentNode.removeChild(obj); //移除当前对象

7、select选择的响应事件

$("#mySelect").change(function(){
     //添加所需要执行的操作代码
})

8、遍历option和添加、移除option

function changeShipMethod(shipping){
 var len = $("select[@name=ISHIPTYPE] option").length
 if(shipping.value != "CA"){
  $("select[@name=ISHIPTYPE] option").each(function(){
   if($(this).val() == 111){
    $(this).remove();
   }
  });
 }else{
  $("<option value='111'>UPS Ground</option>").appendTo($("select[@name=ISHIPTYPE]"));
 }
}

9、取得下拉选单的选取值

$('#testSelect option:selected').text();
或$("#testSelect").find('option:selected').text();
或$("#testSelect").val();

10、添加双击事件

双击select下拉列表选项  
                $('#selectedUsers').dblclick(function(){  
                   $('#selectedUsers option:selected').remove();  
                }).mousedown(function(e){  
                    // 右击  
                   if (e.which == 3){  
                       $(this).children("option:selected").remove();  
                    }  
                }).bind("contextmenu",function(){return false;}); // 该组件禁用右键菜单(Firefox会触发右键菜单);  

 

 


 

 

posted @ 2017-08-14 11:39  cpcpc  阅读(1311)  评论(0)    收藏  举报