jQuery实现Select多选列表双击选中项时相互添加
来源:互联网 发布:开罗旅游自助攻略知乎 编辑:程序博客网 时间:2024/06/10 14:33
jQuery实现在左边双击某一项时添加到右边,右边时添加到左边:
部分修饰代码简略:
<table style="..."><tr><td colspan="2" valign="top" width="47%"> <select multiple="multiple" id="uncountryTable" name="uncountryTable" style="height:300px;width:245px;"></select></td><td align="center">...</td><td colspan="2" valign="top" width="47%"><select multiple="multiple" id="countryTable" name="countryTable" style="height:300px;width:245px;"></select></td></tr></table>
以左边为例:
刚开始我的思路是这样的:当左边select变化时,如果有一项选中,那么当它被双击时就执行相应的操作;但当实施时才发现这样根本不可行,代码如下:
//jQuery("#uncountryTable").change(function(){//jQuery("#uncountryTable option").each(function(){//if(jQuery(this).attr("selected") == true){//jQuery(this).dblclick(function(){//alert(111111);//var option = "<option value='"+jQuery(this).val()+"'>"+jQuery(this).text()+"</option>";//jQuery("#countryTable").append(option);//jQuery(this).remove();//});//}//});//});
其实一直到判断选中的这一步都是正确的,经测试此时也确实可以alert出相应选中项的值
(多选下拉框获取选中文本、value: 也可以用change方法)
//jQuery("#uncountryTable").change(function(){//jQuery("#uncountryTable option").each(function(){//if(jQuery(this).attr("selected") == true){//alert(jQuery(this).val()+":"+jQuery(this).text());//}//});//});
但是一到dblclick(fn)方法这步就有问题了,连测试的111111都不弹出,几经测试都无效果,无奈只得另谋它路。
在网上搜了一下,发现一个哥们用JS写的同样效果代码(下面),看了之后才发现原来自己想得太复杂了,正确思路应该是这样的:当双击select的时候,触发dblclick(fn)事件,如果某一项被选中(你双击某一项,它就肯定被选中啦),就将其添加到右边,这样就可以实现效果,哈哈。
上代码:
jQuery(document).ready(function() {jQuery("#uncountryTable").dblclick(function(){jQuery("#uncountryTable option:selected").each(function(){var option = "<option value='"+jQuery(this).val()+"'>"+jQuery(this).text()+"</option>";jQuery("#countryTable").append(option);jQuery(this).remove();});});});
很简单的东西,换下思路就实现了,因此,以后遇到问题时,就先问下自己,是不是我想得太复杂了,哈哈......
那哥们效果+代码(主要部分):
<head> <script> function removeItem(){ var sltSrc=document.getElementById('sltSrc'); var sltTarget=document.getElementById('sltTarget'); for(var i=0;i<sltSrc.options.length;i++) { var tempOption=sltSrc.options[i]; if(tempOption.selected){ sltSrc.removeChild(tempOption); sltTarget.appendChild(tempOption); } } } </script></head><body> <select ondblclick="removeItem();" id="sltSrc" multiple="true"> <option value="a">srcA</option> <option value="b">srcB</option> <option value="c">srcC</option> </select> <select ondblclick="addItem();" id="sltTarget" multiple="true"> <option value="a">targetA</option> <option value="b">targetB</option> <option value="c">targetC</option> </select> <div id="showInfo"></div> <input type="button" value="showSelectOptions" onclick="showSelectOptions();"/></body>
链接:http://www.cnblogs.com/hanxianlong/archive/2009/03/31/1426095.html