Populate dropdown select with array using jQuery

Jquery

Jquery Problem Overview


I am trying to populate a dropdown select with an array using jQuery.

Here is my code:

        // Add the list of numbers to the drop down here
        var numbers[] = { 1, 2, 3, 4, 5};
        $.each(numbers, function(val, text) {
            $('#items').append(
                $('<option></option>').val(val).html(text)
            );            
        // END

But I'm getting an error. The each function is something I am got off this website.

Is it bombing out because I'm using a one-dimensional array? I want both the option and the text to be the same.

Jquery Solutions


Solution 1 - Jquery

Try for loops:

var numbers = [1, 2, 3, 4, 5];

for (var i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}

Much better approach:

var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
   option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);

Solution 2 - Jquery

The array declaration has incorrect syntax. Try the following, instead:

var numbers = [ 1, 2, 3, 4, 5]

The loop part seems right

$.each(numbers, function(val, text) {
            $('#items').append( $('<option></option>').val(val).html(text) )
            }); // there was also a ) missing here

As @Reigel did seems to add a bit more performance (it is not noticeable on such small arrays)

Solution 3 - Jquery

You can also do this:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 

Solution 4 - Jquery

A solution is to create your own jquery plugin that take the json map and populate the select with it.

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

 $("....").fillValues({datas:your_map,});

Et voila !

You can add functions in your plugin as you like

Solution 5 - Jquery

var qty = 5;
var option = '';
for (var i=1;i <= qty;i++){
   option += '<option value="'+ i + '">' + i + '</option>';
}
$('#items').append(option);

Solution 6 - Jquery

The solution I used was to create a javascript function that uses jquery:

This will populate a dropdown object on the HTML page. Please let me know where this can be optimized - but works fine as is.

function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
{
	var options = '';

	// Create the list of HTML Options
	for (i = 0; i < sourceListObject.List.length; i++)
	{
		options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
	}

	// Assign the options to the HTML Select container
	$('select#' + targetDropDownName)[0].innerHTML = options;

	// Set the option to be Selected
	$('#' + targetDropDownName).val(valueToSelect);

	// Refresh the HTML Select so it displays the Selected option
	$('#' + targetDropDownName).selectmenu('refresh')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 7 - Jquery

Since I cannot add this as a comment, I will leave it here for anyone who finds backticks to be easier to read. Its basically @Reigel answer but with backticks

var numbers = [1, 2, 3, 4, 5];
var option = ``;
for (var i=0;i<numbers.length;i++){
   option += `<option value=${numbers[i]}>${numbers[i]}</option>`;
}
$('#items').append(option);

Solution 8 - Jquery

function validateForm(){
	var success = true;
	resetErrorMessages();
	var myArray = [];
	$(".linkedServiceDonationPurpose").each(function(){
		myArray.push($(this).val())
	});
	
	$(".linkedServiceDonationPurpose").each(function(){
	for ( var i = 0; i < myArray.length; i = i + 1 ) {
		for ( var j = i+1; j < myArray.length; j = j + 1 )
			if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
				$(this).next( "div" ).html('Duplicate item selected');
				success=false;
		   }
		} 
	});
	if (success) {
		return true;
	} else {
        return false;
	}
	function resetErrorMessages() {
		$(".error").each(function(){
			$(this).html('');
		});``
	}
}

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
QuestioncosonView Question on Stackoverflow
Solution 1 - JqueryReigelView Answer on Stackoverflow
Solution 2 - JqueryFabiano SorianiView Answer on Stackoverflow
Solution 3 - JqueryCheesoView Answer on Stackoverflow
Solution 4 - JqueryflorexView Answer on Stackoverflow
Solution 5 - JqueryEd BarahonaView Answer on Stackoverflow
Solution 6 - Jqueryuser3912028View Answer on Stackoverflow
Solution 7 - JquerySeal_SealView Answer on Stackoverflow
Solution 8 - JquerysrikanthView Answer on Stackoverflow