I can't make this little script work: Fiddle
I want to pass selected options from a Multiple Select to another using buttons.
I think there is a problem with jQuery selector when trying to select all "option:selected
".
HTML :
<div>
<select id='canselect_code' name='canselect_code' multiple>
<option value='1'>toto</option>
<option value='2'>titi</option>
</select>
<input type='button' id='btnRight_code' value=' > ' />
<br>
<input type='button' id='btnLeft_code' value=' < ' />
<select id='isselect_code' name='isselect_code' multiple>
<option value='3'>tata</option>
<option value='4'>tutu</option>
</select>
</div>
JS
$('[id^=\"btnRight\"]').click(function (e) {
var selectedOpts = $(this).prev('select option:selected');
if (selectedOpts.length === 0) {
alert('Nothing to move.');
e.preventDefault();
} else {
$(this).next('select').append($(selectedOpts).clone());
$(selectedOpts).remove();
}
});
$('[id^=\"btnLeft\"]').click(function (e) {
var selectedOpts = $(this).next('select option:selected');
if (selectedOpts.length === 0) {
alert('Nothing to move.');
e.preventDefault();
} else {
$(this).prev('select').append($(selectedOpts).clone());
$(selectedOpts).remove();
}
});
The "_code" mention is in my app a dynamic code, that's why i use [^selector]
instead direct id selectors like (#)
.
I managed to get it working rewriting all your code into neat one liner.
JSFiddle: (MOVE option to the other element) - http://jsfiddle.net/GJJQw/
JSFiddle: (COPY option to the other element) - http://jsfiddle.net/dEE7A/
The below code COPIES
the select elements into the other select box.
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').clone().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').clone().appendTo('#canselect_code');
});
If you wanted to MOVE
(ie delete from one, and add to the other).. Use this:
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
});
// the button that was clicked
$(this)
// .next('select') = get the next <select> element
.next('select').
// .find('option:selected') = get all the selected options
.find('option:selected')
// .remove() [or .clone()] = Remove or clone the found options
.remove() // OR .clone()
// .appendTo('#id-of-element') = Append the found elements to the other select box
.appendTo('#canselect_code');
So by changing the .remove()
to .clone()
you will COPY the option to the other select, otherwise remove()
will remove it from this select element, and append it to the other.
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