Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  31] [ 2]  / answers: 1 / hits: 151730  / 14 Years ago, tue, may 4, 2010, 12:00:00

I have the below functions in regular JavaScript creating select options. Is there a way I can do this with jQuery without having to use the form object? Perhaps storing the options as an array of JSON objects and parsing this in the calling function...



function populate(form)
{
form.options.length = 0;
form.options[0] = new Option(Select a city / town in Sweden,);
form.options[1] = new Option(Melbourne,Melbourne);
}


Below is how I call the function above:



populate(document.form.county); //county is the id of the dropdownlist to populate.    

More From » jquery

 Answers
38

Something like:



function populate(selector) {
$(selector)
.append('<option value=foo>foo</option>')
.append('<option value=bar>bar</option>')
}

populate('#myform .myselect');


Or even:



$.fn.populate = function() {
$(this)
.append('<option value=foo>foo</option>')
.append('<option value=bar>bar</option>')
}

$('#myform .myselect').populate();

[#96882] Sunday, May 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;