Reputation: 373
I'm trying to copy the <options>
HTML Codes from one select list to another. I have tested the script below, but it does not work.
I have tested with an 'alert' function, but it seems to only display the values within the previous options.
would anyone be able to recommend what I should use? Thank you!
$("select[name='NHIndexNo" + tablecounter + "_" + rowCount + "'] option").each(function(){
$("select[name='NHIndexNo" + tablecounter + "_" + (rowCount+1) + "'] option").appendto($(this).val());
});
Upvotes: 3
Views: 8722
Reputation: 5198
jQuery:
$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').remove().appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').remove().appendTo('#select1');
});
});
HTML:
<div>
<select multiple id="select1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
<a href="#" id="add">add >></a>
</div>
<div>
<select multiple id="select2"></select>
<a href="#" id="remove"><< remove</a>
</div>
Demo: http://jsfiddle.net/LbPAq/1
Upvotes: 4
Reputation: 47667
Simply try - http://jsfiddle.net/zDFdX/
$("#stwo").html( $("#sone").html() );
HTML
<select id="sone">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="stwo">
</select>
Upvotes: 6
Reputation: 253308
Without seeing your HTML, and I'm therefore only able to guess that your selectors are working appropriately, I'd suggest:
$("select[name='NHIndexNo" + tablecounter + "_" + (rowCount+1) + "'] option").clone(true).appendTo($(this).val());
The idea is that you clone the elements (matching the selector) and then append the clone to the other select
element.
Note, also, that I've passed true
(the withDataAndEvents
parameter) into the clone()
method; this is to copy across the data and events allocated to those elements with jQuery. Omit this parameter if you're not concerned about those being cloned.
References:
Upvotes: 0
Reputation: 816322
Clone the elements before you append them to the other select element:
$("select[name='NHIndexNo" + tablecounter + "_" + rowCount + "'] option")
.clone() // <-- creates a copy of each selected element
.appendTo("select[name='NHIndexNo" + tablecounter + "_" + (rowCount+1) + "']");
Since you don't provide any context information or markup, I assume that the selectors are correct.
Upvotes: 0
Reputation: 7013
$("select[name='NHIndexNo" + tablecounter + "_" + rowCount + "'] option").each(function(){
$("select[name='NHIndexNo" + tablecounter + "_" + (rowCount+1) + "']").append($(this).clone());
});
You had it almost right
Upvotes: 0