Saturday, 15 February 2014

javascript - An efficient way to repopulate a select box? -



javascript - An efficient way to repopulate a select box? -

i've got good'n'old double select box , wondering what's efficient way remove options , include new ones. current approach (jquery-less suggestions welcomed):

class="lang-js prettyprint-override">var citiesselect = $('#cities'), cities = ['a bunch', 'of', 'cities'], //would come external array of ajax option; citiesselect.find('option').each(function() { $(this).remove(); }); cities.unshift('---'); //including blank alternative (i in cities) { alternative = document.createelement('option'); option.value = i; option.innertext = cities[i]; citiesselect.append(option); }

   

edit: results

this jsperf resulted question (that's buried answers' comments).

one of efficient ways add together lot of dom elements @ 1 time utilize document fragment. mdn

var citiesselect = $('#cities'), cities = ['a bunch', 'of', 'cities'], //would come external array of ajax option, frag = document.createdocumentfragment(); citiesselect.empty(); cities.unshift('---'); //including blank alternative (var = 0;i < cities.length; i++){ alternative = document.createelement('option'); option.value = i; option.innertext = cities[i]; frag.appendchild(option); } citiesselect.append(frag);

i added test case @jack's jsperf http://stackoverflow.com/users/680420/jack

and here fiddle

javascript jquery html performance

No comments:

Post a Comment