[javascript] Adding options to a <select> using jQuery?

This is just a quick points for best performance

always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

f.g.

var $mySelect = $('#mySelect'); var str = '';

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string

$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');

Even faster

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery