jQuery选择和取消选择多个输入,而无需按Ctrl [英] jquery select and unselect multiple input without ctrl click
问题描述
这是场景:
<select id="id_user" name="user" multiple="multiple">
<option value="1">User 1</option>
<option value="2">User 2</option>
<option value="3">User 3</option>
<option value="4">User 4</option>
</select>
<span id="select1">Select 1 user</span> <span id="remove1">Remove 1 select</span>
<span id="select2">Select 2 user</span> <span id="remove2">Remove 2 select</span>
<span id="select3">Select 3 user</span> <span id="remove3">Remove 3 select</span>
<span id="select4">Select 4 user</span> <span id="remove4">Remove 4 select</span>
<script type="text/javascript">
$("#select1").click(function(){ $("#id_user").val("1").prop("selected", true);
???
});
$("#remove1").click(function(){ $("#id_user").val("1").prop("selected", false);
???
});
</script>
例如,我想让用户单击选择1个跨度",然后单击选择2个跨度",并且将在多个选择中同时选择两者选项.然后,如果用户单击删除1选择范围",则仅选择1"将被删除.我不知道如何完成这项任务.当我使用#select2,#select3(...)创建其他点击函数时,单击一个选择,将删除最后一次选择的选项.同样的问题是删除选项.如何创建Ctrl单击效果?
I want to let user for example to click on Select 1 span, then click on Select 2 span and both options will be selected in multiple select. Then if user click Remove 1 select span, only Select 1 will be removed. I don't have an idea how to complete that task. When I create other click functions with #select2, #select3 (...), clicking on one select, removes option selected with last click. Same problem is with remove option. How to create Ctrl-click effect ?
推荐答案
您可以动态生成控件...(请参见现场演示):
You can generate your controls dynamically... (see live demo) :
<div id="selectControls"></div>
<script type="text/javascript">
$(function() {
$('#id_user > option').each(function() {
var $this = $(this);
$('#selectControls').append($('<span></span>')
.text("Select " + $this.val() + " user")
.click(function() { $this.attr('selected', true); $('#id_user').focus(); })
).append(' ').append($('<span></span>')
.text("Deselect " + $this.val() + " user")
.click(function() { $this.removeAttr('selected'); $('#id_user').focus(); })
).append('<br />');
});
});
</script>
生成自己的控件不仅是一个更好的解决方案,而且如果您在列表中添加/删除OPTION
元素,则可以避免维护...并且如果选择范围扩大,可以缩短HTML从服务器下载的时间.
Generating your own controls is not only a better solution, it avoids maintenance if you add/remove OPTION
element in the list... and keep HTML shorter to download from the server if your selection grows.
这篇关于jQuery选择和取消选择多个输入,而无需按Ctrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!