当前位置: 代码迷 >> JavaScript >> 如何用js去除和添加下拉框选项
  详细解决方案

如何用js去除和添加下拉框选项

热度:204   发布时间:2012-03-23 12:06:21.0
怎么用js去除和添加下拉框选项?
如题:有两个下拉框:
<select name="left" multiple="multiple" size="25" style='width:130px;'>
  <option value="">请选择</option>
  <option value="">请选择</option>
  <option value="">请选择</option>
</select> 
<select name="right" multiple="multiple" size="25" style='width:130px;'>
  <option value="">从左侧选择</option>
</select> 
怎么把选择的left选项添加到right中,同时把left中被选中的删除?用js怎么实现?在线等,知道的,指点下,最好贴出js代码,先谢过了,急用、、、、

------解决方案--------------------
<html>
<head>
<title></title>
<script type='text/javascript'>
function selectItem() {
var left = document.getElementsByName("left")[0];
var right = document.getElementsByName("right")[0];
left.ondblclick = function () {
var text = this.options[this.selectedIndex].text;
right.options.add(new Option(text, text));
this.removeChild(this.options[this.selectedIndex]);
}
}
window.onload = selectItem;
</script>
</head>
<body>
<h4>请双击左侧选项进行选择</h4>
<select name="left" multiple="multiple" size="25" style='width: 130px;'>
<option value="">请选择1</option>
<option value="">请选择2</option>
<option value="">请选择3</option>
</select>
<select name="right" multiple="multiple" size="25" style='width: 130px;'>
<option value="">从左侧选择</option>
</select>
</body>
</html>
------解决方案--------------------

var op = document.createElement("OPTION");
op.value = document.left.value;
right.options.add(op)

document.all.left.remove(left.selectedIndex);
------解决方案--------------------
HTML code
<HTML>
    <HEAD>
        <TITLE>main</TITLE>
        <script type="text/javascript">
            
            function transferOpt()
            {
                var _left=document.getElementsByName("left")[0];   
                var _right=document.getElementsByName("right")[0];     
                if(_left.selectedIndex!=-1)
                {                    
                    var _opt=_left[_left.selectedIndex];
                    _right.appendChild(_opt);                  
                }        
            }

        </script>        
    </HEAD>

    <body>
        <select name="left" multiple="multiple" size="25" style='width:130px;' ondblclick="transferOpt()">
          <option value="">请选择</option>
          <option value="">请选择</option>
          <option value="">请选择</option>
        </select>  
        <select name="right" multiple="multiple" size="25" style='width:130px;'>
          <option value="">从左侧选择</option>
        </select>  
    </body>
</HTML>

------解决方案--------------------
我用的是jquery
清空select
$("#id").option.length=0
新增
$("#id").option[0]=new option('dddd','dddd')
  相关解决方案