jQuery: Best practice to populate drop down?

JquerySelect

Jquery Problem Overview


The example I see posted all of the time seems like it's suboptimal, because it involves concatenating strings, which seems so not jQuery. It usually looks like this:

$.getJSON("/Admin/GetFolderList/", function(result) {
	for (var i = 0; i < result.length; i++) {
		options += '<option value="' + result[i].ImageFolderID + '">' + result[i].Name + '</option>';
	}
});

Is there a better way?

Jquery Solutions


Solution 1 - Jquery

Andreas Grech was pretty close... it's actually this (note the reference to this instead of the item in the loop):

var $dropdown = $("#dropdown");
$.each(result, function() {
	$dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

Solution 2 - Jquery

$.getJSON("/Admin/GetFolderList/", function(result) {
    var options = $("#options");
    //don't forget error handling!
    $.each(result, function(item) {
        options.append($("<option />").val(item.ImageFolderID).text(item.Name));
    });
});

What I'm doing above is creating a new <option> element and adding it to the options list (assuming options is the ID of a drop down element.

PS My javascript is a bit rusty so the syntax may not be perfect

Solution 3 - Jquery

Sure - make options an array of strings and use .join('') rather than += every time through the loop. Slight performance bump when dealing with large numbers of options...

var options = [];
$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options.push('<option value="',
          result[i].ImageFolderID, '">',
          result[i].Name, '</option>');
    }
    $("#theSelect").html(options.join(''));
});

Yes. I'm still working with strings the whole time. Believe it or not, that's the fastest way to build a DOM fragment... Now, if you have only a few options, it won't really matter - use the technique Dreas demonstrates if you like the style. But bear in mind, you're invoking the browser's internal HTML parser i*2 times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you'll end up paying for it, especially on older browsers.

Note: As Justice points out, this will fall apart if ImageFolderID and Name are not encoded properly...

Solution 4 - Jquery

Or maybe:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});

Solution 5 - Jquery

The fastest way is this:

 $.getJSON("/Admin/GetFolderList/", function(result) {
		var optionsValues = '<select>';
        $.each(result, function(item) {
			optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>';
        });
		optionsValues += '</select>';
		var options = $('#options');
		options.replaceWith(optionsValues);
    });

According to this link is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.

Solution 6 - Jquery

I found this to be working from jquery site

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});

Solution 7 - Jquery

I've read that using document fragments is performant because it avoids page reflow upon each insertion of DOM element, it's also well supported by all browsers (even IE 6).

var fragment = document.createDocumentFragment();

$.each(result, function() {
  fragment.appendChild($("<option />").val(this.ImageFolderID).text(this.Name)[0]);
});

$("#options").append(fragment);

I first read about this in CodeSchool's JavaScript Best Practices course.

Here's a comparison of different approaches, thanks go to the author.

Solution 8 - Jquery

Other approach with ES6

fetch('https://restcountries.eu/rest/v1/all')
  .then((response) => {
    return response.json()
  })
  .then((countries) => {
    var options = document.getElementById('someSelect');
    countries.forEach((country) => {
      options.appendChild(new Option(country.name, country.name));
    });
  })

Solution 9 - Jquery

I hope it helps. I usually use functions instead write all code everytime.

    $("#action_selector").change(function () {
        
        ajaxObj = $.ajax({
            url: 'YourURL',
            type: 'POST', // You can use GET
            data: 'parameter1=value1',
            dataType: "json",
            context: this,                
            success: function (data) {
                json: data              
            },
            error: function (request) {
                $(".return-json").html("Some error!");
            }
        });

        json_obj = $.parseJSON(ajaxObj.responseText);            

        var options = $("#selector");
        options.empty();
        options.append(new Option("-- Select --", 0));
        $.each(ajx_obj, function () {
            options.append(new Option(this.text, this.value));
        });
    });
});

Solution 10 - Jquery

I use the selectboxes jquery plugin. It turns your example into:

$('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);

Solution 11 - Jquery

$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
	            document.getElementById("select1").options[i+1] = new Option(sary[i]);
	            document.getElementById("select1").options[i+1].value = sary[i];
	        }
            });

Solution 12 - Jquery

function LoadCategories() {
    var data = [];
    var url = '@Url.Action("GetCategories", "InternalTables")';
    $.getJSON(url, null, function (data) {
        data = $.map(data, function (item, a) {
            return "<option value=" + item.Value + ">" + item.Description + "</option>";
        });
        $("#ddlCategory").html('<option value="0">Select</option>');
        $("#ddlCategory").append(data.join(""));
    });
}

Solution 13 - Jquery

function generateYears() {
                    $.ajax({
                        type: "GET",
                        url: "getYears.do",
                        data: "",
                        dataType: "json",
                        contentType: "application/json",
                        success: function(msg) {
                            populateYearsToSelectBox(msg);
                        }
                    });
}

function populateYearsToSelectBox(msg) {
  var options = $("#selectYear");
$.each(msg.dataCollecton, function(val, text) {
   options.append(
        $('<option></option>').val(text).html(text)
    );
});
}

Solution 14 - Jquery

here is an example i did on change i get children of the first select in second select

jQuery(document).ready(function($) {
$('.your_select').change(function() {
	$.ajaxSetup({
        headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
    });

    $.ajax({
        type:'POST',
        url: 'Link',
        data:{
          'id': $(this).val()
        },
        success:function(r){
          $.each(r, function(res) {
          		console.log(r[res].Nom);
          		 $('.select_to_populate').append($("<option />").val(r[res].id).text(r[res].Nom));
			});
        },error:function(r) {
          alert('Error');
        }
    });
});

});enter code here

Solution 15 - Jquery

For a newbie like me to JavaScript let alone JQuery, the more JavaScript way of doing it is:

result.forEach(d=>$("#dropdown").append(new Option(d,d)))

Solution 16 - Jquery

I have been using jQuery and calling a function to populate drop downs.

function loadDropDowns(name,value)
{
   var ddl = "#Categories";
   $(ddl).append('<option value="' + value + '">' + name + "</option>'");
}

Solution 17 - Jquery

Below is the Jquery way of populating a drop down list whose id is "FolderListDropDown"

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        var elem = $("<option></option>");
        elem.attr("value", result[i].ImageFolderID);
        elem.text(result[i].Name);
        elem.appendTo($("select#FolderListDropDown"));
     }
});

Solution 18 - Jquery

You can create options from SQL side (coalesce) and return as string and append that string to drop-down You can remove loop in the code. Ie, if you are using any back end like SQL server You can create options tag using coalesce Ie you will get a string containing entire option

Then you can return the entire string from back end and append to your drop-down

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff PutzView Question on Stackoverflow
Solution 1 - JqueryJeff PutzView Answer on Stackoverflow
Solution 2 - JqueryAndreas GrechView Answer on Stackoverflow
Solution 3 - JqueryShog9View Answer on Stackoverflow
Solution 4 - JqueryxinthinkView Answer on Stackoverflow
Solution 5 - JqueryRicibaldView Answer on Stackoverflow
Solution 6 - JquerybinshiView Answer on Stackoverflow
Solution 7 - JqueryDapeng LiView Answer on Stackoverflow
Solution 8 - JqueryIsrael PeralesView Answer on Stackoverflow
Solution 9 - JqueryPablo Rocha VillagraView Answer on Stackoverflow
Solution 10 - JqueryBrian YargerView Answer on Stackoverflow
Solution 11 - JquerysunilView Answer on Stackoverflow
Solution 12 - JqueryDeenathaiyalan ShanmugamView Answer on Stackoverflow
Solution 13 - JqueryDulacosteView Answer on Stackoverflow
Solution 14 - JqueryAbdelghafour EnnahidView Answer on Stackoverflow
Solution 15 - JquerytashView Answer on Stackoverflow
Solution 16 - JqueryElimGarakView Answer on Stackoverflow
Solution 17 - JqueryHang YuView Answer on Stackoverflow
Solution 18 - JqueryShyamView Answer on Stackoverflow