What\'s the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$(\"#mySelect\").append(\'
If someone comes here looking for a way to add options with data properties
Using attr
var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);
Using data - version added 1.2.3
var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);
You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.
$('#select').append($('<option>', {value:1, text:'One'}));
$('#select').append('<option value="1">One</option>');
var option = new Option(text, value); $('#select').append($(option));
This is very simple:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
To help performance you should try to only alter the DOM once, even more so if you are adding many options.
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);
This is the way i did it, with a button to add each select tag.
$(document).on("click","#button",function() {
$('#id_table_AddTransactions').append('<option></option>')
}
Why not simply?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')