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.
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.
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.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With