Here's the scenario:
<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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With