JavaScript: Dynamically Add Options to an HTML Select Using jQuery

Here’s how you can dynamically add options to an HTML select using jQuery

 
var $selector = $('#mySelect');
$selector.append($('<option>', { value: "" }).text("-- Choose --"));
$.each(this.dataArray, function (idx, dataItem) {
	$selector.append($('<option>', { value: dataItem.Key }).text(dataItem.Value));
});
$selector.append($('<option>', { value: "All" }).text("Show All"));
$selector.change(function () {
	alert('Selected ' + $(this).val());
});

Hope this helps!

This entry was posted in JavaScript, jQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *