What\'s the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$(\"#mySelect\").append(\'
$(function () {
var option = $("<option></option>");
option.text("Display text");
option.val("1");
$("#Select1").append(option);
});
If you getting data from some object, then just forward that object to function...
$(function (product) {
var option = $("<option></option>");
option.text(product.Name);
option.val(product.Id);
$("#Select1").append(option);
});
Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers
There are two ways. You can use either of these two.
First:
$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
Second:
$.each(dataCollecton, function(val, text) {
options.append($('<option></option>').val(text.route).html(text.route));
});
If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
I like to use non jquery approach:
mySelect.add(new Option('My option', 1));
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:
$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");
$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected
$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected