Mark Kadlec
Mark Kadlec

Reputation: 8460

How to move large amount of select options to another select control using javascript?

I have a link above a duel list box control that is 'Select All'. The functionality is to move the <select> options from one select to another select.

The jQuery moves from the source to the destination and has worked fine, but now there are over 100,000 records in the source <select>, and causes a

Uncaught RangeError: Maximum call stack size exceeded

in Chrome and an unresponsive script popup in Firefox. Here is the jQuery:

$('#' + source + ' option').remove().appendTo('#' + destination).removeAttr('selected');

Is there a way I can do this to limit the impact on the browser and not cause problems with large amount of <option>s?

Upvotes: 1

Views: 187

Answers (2)

user5037156
user5037156

Reputation:

I don't have enough reputation to comment but would like to join the discussion. I can't even seem to build a select statement that can open in google chrome using jquery. My code is

function selectBuild() {
html = '<select id="select1">';
for (i=0;i<100001;i++) {
    html += '<option>' + i + '</option>';
}
html += '</select>';
$('#selectdiv').html(html);
html ='';
}

Perhaps you could iterate all of the options to an array and reprint that array? SOmething like

var options = new Array();
$('#'+source+' option').each(function() { options.push($(this).val()); });
html = '<select id="' + destination + '">';
$(options).each(function(index,value) { html+='<option>'+value+'</option>'; });
html += '</select>';

$('#div').html(html);

Upvotes: 3

efarley
efarley

Reputation: 8661

Rather than parsing row by row I'd just copy the entire HTML from the source to the destination and then delete the html from the source. I'm not totally sure what you're doing with the active class but you can probably just add a addClass() or removeClass() as nessecary.

$('#' + destination).html($('#' + source + ' option').html());
$('#' + source + ' option').html('');

Here's a jsFiddle with a working example, all though it doesn't have 100,000 options. https://jsfiddle.net/j9qtej9r/

Upvotes: 2

Related Questions