What's the easiest way to add an option to a dropdown using jQuery?
Will this work?
$("#mySelect").append('<option value=1>My option</option>');
Personally, I prefer this syntax for appending options:
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});
This did NOT work in IE8 (yet did in FF):
$("#selectList").append(new Option("option text", "value"));
This DID work:
var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
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));
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');
This is very simple:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
Option 1-
You can try this-
$('#selectID').append($('<option>',
{
value: value_variable,
text : text_variable
}));
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append($('<option>',
{
value: i,
text : "Option "+i
}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
Option 2-
Or try this-
$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );
Like this-
for (i = 0; i < 10; i++)
{
$('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
That works well.
If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.
for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+
I had to use $("#myselect").html("<option value='text'>text</option>");
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);
Why not simply?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
Test here:
for (let i=0; i<10; i++) {
$('<option/>').val(i).text('option ' + i).appendTo('#mySelect')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect"></select>
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
I like to use non jquery approach:
mySelect.add(new Option('My option', 1));
var select = $('#myselect');
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
};
$('option', select).remove();
$.each(newOptions, function(text, key) {
var option = new Option(key, text);
select.append($(option));
});
You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot
Output:
var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
var myselect = $('<select>');
$.each(resultData, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="selectCity">
</select>
Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:
var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
If you want to insert the new option at a specific index in the select:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
This will insert the "New Item" as the 3rd item in the select.
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));
});
You can append and set the Value attribute with text:
$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
How about this
var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);
if u have optgroup inside select, u got error in DOM.
I think a best way:
$("#select option:last").after($('<option value="1">my option</option>'));
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
$(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
Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select id="selectCity"></select>
Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!
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);
$('#select_id').append($('<option>',{ value: v, text: t }));
This is just a quick points for best performance
always when you are dealing with many options, build a big string and then add it to the 'select' for best performance
f.g.
var $mySelect = $('#mySelect');
var str = '';
$.each(items, function (i, item) {
// IMPORTANT: no selectors inside the loop (for the best performance)
str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string
$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');
Even faster
var str = "";
for(var i; i = 0; i < arr.length; i++){
str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}
$mySelect.html(str);
$mySelect.multiSelect('refresh');
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>')
}
You can do this in ES6:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});
Try
mySelect.innerHTML+= '<option value=1>My option</option>';
btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
<button id="btn">Add option</button>
<select id="mySelect"></select>
U can try below code to append to option
<select id="mySelect"></select>
<script>
$("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
</script>
I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});
You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
I have a survey-type form that's being populated from a web database on the client. I can populate the questions fine, but then I try to go through and trigger the click event where there is an existing answer (edit scenario), I'm finding that the new elements are not yet in the DOM so this doesn't work. Here's the code:
$(function() {
var db = openDatabase(...);
db.transaction(function(tx) {
tx.executeSql("select ....", [surveyId], function(tx, results) {
var items = "", answers = [];
for (var i = 0; i < results.rows.length; i++) {
var id = results.rows.item(i).id;
items += "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' /><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' /><label for='q-"+id+"-2'>No</label></div>";
if (result.rows.item(i).answer) {
answers.push('#q-'+id+'-'+results.rows.item(i).answer);
}
}
$('#questions-div').append(items);
$.each(answers, function(i, e) { $(e).click(); });
});
});
});
Any tips how I can make this work, or better generally?
I think here:
answers.push('#q-'+id+'-'+result);
You meant to push this:
answers.push('#q-'+id+'-'+result.rows.item[i].answer);
Otherwise you're getting '#q-XX-[object Object]' as a selector, where I think you're after the 1 or 2 version of '#q-XX-1'.
I suspect this is actually a race condition. My bet is that if you execute your each statement after a tiny delay, things will work as expected. Is so, the reason for this is that you can't be 100% sure when the browser will actually get around to updating the DOM when you programmaticallly insert new elements. I'm not sure what the best solution would be: if you were attaching events, I'd say you should do it at the same time you are building the elements; but if you are triggering the clicks, I'm leaning toward just continually testing for the existance of the elements and then triggering the clicks as soon as you know they are there.
So I came up with a solution:
I replaced the line items += "<div> ...." with
var item = "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' ";
if (results.rows.item(i).answer == 1) item += "checked ";
item += "/><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' ";
if (results.rows.item(i).answer == 2) item += "checked ";
item += "/><label for='q-"+id+"-2'>No</label></div>";
items += item;
... which means I no longer need the answers array or to trigger click events on the radio buttons.
I was hoping for something a bit neater, but this seems to work OK. Thanks #Nick Craver & #Andrew for helping me arrive at it!