Reputation: 45485
We want to make a new select box and copy its options from another select box when an event happens. We use below code:
//Create a new select box and add it to a div
$('#content').append("<select id='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$("#destination").append($options);
http://jsfiddle.net/e8ctkkvL/1/
I have a page with lots of selects(each with lots of options), above code is slow ! Is there any way I can make above JS faster ?!
Upvotes: 0
Views: 120
Reputation: 8181
I'd rather copy the source and set a dynamic id since you may want to have multiple select boxes and different IDs, like below:
Demo@Fiddle
$(document).ready(function () {
var id = 1;
$("#btn").click(function () {
//Create a new select box
$('#content').append($("#source").clone(true).attr({id: "destination" + id}));
id++;
});
});
Upvotes: 1
Reputation: 10219
You should set a class instead of an ID and then append it to the last created select, for example:
$(document).ready(function () {
$("#btn").click(function () {
//Create a new select box
$('#content').append("<select class='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$(".destination").last().append($options);
});
});
Fiddle: http://jsfiddle.net/e8ctkkvL/3/
Upvotes: 1