Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery create new select option

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.     
like image 206
van Avatar asked May 04 '10 17:05

van


People also ask

How to create option for select with jQuery?

The Option() constructor is used to create a new option element. A new option is created with the text and the value of the option as the parameters. This element is then added to the select box with the append() method. A new jQuery DOM element is created with the option tag.

How to add dropdown values in jQuery?

Add options to a drop-down list using jQuery. JavaScript Code: var myOptions = { val1 : 'Blue', val2 : 'Orange' }; var mySelect = $('#myColors'); $. each(myOptions, function(val, text) { mySelect.

How to add attribute in option in jQuery?

Answer: Use the jQuery attr() method You can use the jQuery attr() method to add attributes to an HTML element. In the following example when you click on the "Select Checkbox" button it will add the checked attribute to the checkbox dynamically using jQuery.

How to add Select2 in jQuery?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).


1 Answers

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(); 
like image 56
Harold1983- Avatar answered Oct 07 '22 01:10

Harold1983-