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>
Related
How can I append the data from API to a select tag in html.
This is my javascript code.
var options = '';
for (var i = 0; i < data.total; i++) {
options += '<option value="' + data.data[i].projectName + '">' + data.data[i].projectName + '</option>';
}
$("#selectProjectName").append(options);
This is my html code.
<select id="selectProjectName" class="form-control show-tick selectpicker" title="Choose project name">
</select>
The data is shown in the console of the browser, but it is not appended to the select tag while hard coded values are shown in the select tag.
Using AdminBSBMaterialDesign-master template.
It looks that you're using selectpicker, so after you change anything in the select element you need to refresh it using $(".selectpicker").selectpicker("refresh");
This is in the documentation here.
Also, there's nothing apparently wrong with your method of appending it, as long as data.total returns the length of it (otherwise, use .length) but just as a FYI you can use the following syntax:
$('#select').append($('<option>', {value:1, text:'One'}));
To make things easier and nicer for you.
Cheers! :)
I assume your data is key value type
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
}; // get this data from server
var selectedOption = 'green';
var select = $('#selectProjectName');
var options = select.prop('options');
$.each(newOptions, function(val, text) {
options[options.length] = new Option(text, val);
});
select.val(selectedOption);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectProjectName" class="form-control show-tick selectpicker" title="Choose project name">
</select>
Try .length instead of .total
var options = '';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].projectName + '">' + data[i].projectName + '</option>';
}
$("#selectProjectName").append(options);
$("#selectProjectName").selectpicker("refresh");
Instead of using string concatenation, you can use jquery style of creating option element and appending the same as below.
Please check whether your data structure is similar to the one below according to the code that you are trying.
Otherwise better to use data.data.length instead of data.total
var data = {
total: 3,
data: [
{
projectName: 'jquery'
},
{
projectName: 'reactjs'
},
{
projectName: 'angular'
}
]
};
for (var i = 0; i < data.data.length; i++) {
var option = $('<option>', {
value: data.data[i].projectName,
html: data.data[i].projectName
});
$("#selectProjectName").append(option);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectProjectName" class="form-control show-tick selectpicker" title="Choose project name">
</select>
Use .length instead of .total
Inside the loop, create each option element and add them one by one to the select element:
for (var i = 0; i < data.length; i++) {
var opt = $('<option></option>');
opt.attr('value', data.data[i].projectName).text(data.data[i].projectName);
$("#selectProjectName").append(opt);
}
Select2 v4.0 lets you add options to the dropdown dynamically by creating new Option objects and appending them. How can you dynamically add data which has more than just an id and text?
More specifically, if the select2 uses the templateResult configuration to style data with more than just plain text then adding Options is too restrictive. This callback only works with the library's own data format.
$('#select2').select2({
templateResult: function(data) {
return data.text + ' - ' + data.count;
}
});
$('#select2').append(new Option('Item', 1, false, false));
I'd like to add more complex data when the dropdown is opened and template the results.
I've tried some ugly workarounds, such as
var opt = new Option('Item', 1, false, false);
opt.innerHTML = '<div>Item</div><div>Count</div>';
But the HTML gets stripped and select2 displays plain text.
The library's maintainer states there is not going to be any support for this feature, as reported in a closed Github issue . The only reasonable workaround I've found is to re-initialize the element after it's populated:
function initSelect2(data) {
var select = $('#select2');
select.select2({
templateResult: function(data) {
return data.text + ' - ' + data.count;
});
if (data.length) {
select.data('loaded', 1);
select.select2('open');
} else {
select.on('select2.opening', fillSelect2);
}
function fillSelect2() {
var select = $('#select2');
if (select.data('loaded')) {
return;
}
var data = [];
var data.push({id: 1, text: 'One', count: 1});
var data.push({id: 2, text: 'Two', count: 2});
var data.push({id: 3, text: 'One', count: 3});
initSelect2(data);
}
initSelect2();
Maybe just using the standard html/jQuery and customize whatever you need.
$('#select2').append("<option value='"+ id +"'>" + text+ "</option>");
Please help i am doing this to use in my mobile with jquery mobile
var obj = jQuery.parseJSON(finalresult);
//alert(obj);
var dept = '2';
$(document).ready(function () {
//$("#opsContactId").empty();
$.each(obj, function (k, v) {
var $opt = $("<option/>");
$opt.attr("value", k);
//alert(k);
//alert(v);
//var value1=v;
if (k == dept) {
//$opt.attr("selected","selected");
//alert("in if");
$("#opsContactId").val(k);
//document.getElementById("opsContactId").value=k;
// $('#opsContactId').selectmenu('refresh', true);
}
$opt.text(v);
$opt.appendTo($("#opsContactId"));
});
});
not able to set an option to be selected by dafault
As others as stated, jQuery's .prop() would be the most suitable answer here as jQuery Docs mention themselves:
"The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value."
To further your on your example, jQuery allows for method 'chaining' which returns the jQuery object after the method has completed, thus you can add another method directly after it.
<select id="opsContactId">
</select>
<script>
$(document).ready(function() {
var tmp = [ 1, 2, 3, 4, 5 ],
dept = 2;
$.each( tmp, function( k, v ) {
$("<option/>").attr("value", k)
.text( "Value - " + v)
.appendTo( $("#opsContactId") )
.prop( 'selected', ( k == dept ? 'selected' : '' ));
});
});
</script>
Fiddle: http://jsfiddle.net/twdgC/
Later I forgot you mentioned the jQuery mobile aspect of your question, which changes the dynamic of the question a little bit. The snippet above is run after the page has loaded (Thus, all the jQuery mobile attachments have already been set/made), which would happen to give you the result of (below)
Fiddle: http://jsfiddle.net/5ksG8/
This obviously isn't helpful when trying to construct an <select> list, thus we'll need to append the snippet above with:
$("#opsContactId").selectmenu('refresh', true );
After the snippet has run, thus it 'reloads' the entire list, finally providing you with (below)
Fiddle: http://jsfiddle.net/YxVg6/
You were doing this in your original snippet, the issue was - you were executing it within the loop (And it was commented out!).
Would something like this not be easier?
Would something like this not be easier?
var selected = "selected"; // work this out
var text = "Option Text"; // work this out
var value = "Option Value"; // work this out
$("#opsContactId").append('<option value="' + value + '" '+ selected + '>' + text + '</option>');
jsBin demo
if you have a match you'll need to add the attribute selected. however I don't know how your object looks like...
var obj = {"1":"one","2":"two","3":"three","4":"four"}; // let's say that's how it looks
var dept = '2';
$(function () {
var $sel = $("#opsContactId");
$.each(obj, function (k, v) {
var $opt = $("<option/>", {value:k, text:v}).appendTo( $sel );
if (k == dept) $opt.prop({selected:true});
});
});
The first block of code is a working example of what I want the variable select to do. the var Select is there to be a td in the variable tr. the variable tr is used 2 times in this code. once to to append the tr when the table has html and another time when it doesn't have any html. the reason is because if doesn't have html it should append the header and the row with the select element and the rest of the data that's supposed to be on the row and if does have html it should only append the row to prevent repetition of the header. so I would like a nice clean variable named tr that will be append every time the users invokes it. jsfidle if you click on the drop down you could select the item and the new row will appear.
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var select = " <select class = 'select'><option value='volvo>Volvo</option> <option value='saab'>Saab</option> <option value='mercedes'>Mercedes</option> <option value='audi'>Audi</option> </select>"
var tr = "<tr><td>"+ suggestion.value + "</td><td>" +select +"</td></tr>"
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
The thing is I want the select element to be made up dynamically so i tried something and I cant figure out why it wont work. It's not recieving the variable. Am i implementing the varable wrong with the $.each?
$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = '<strong>Item:</strong> ' + suggestion.value + ' <br> <strong>price:</strong> ' + suggestion.data + "<br>" + suggestion.divs;
var tableheader = ($("<thead>")
.append($("<tr>")
.append($("<th>Item</th><th>Qty</th><th>Price</th>")))
)
var selectValues = { "3": "2", "2": "1" , "1": "..."};
var select = $.each(selectValues, function(key, value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
var tr = "<tr><td>"+ suggestion.value + "</td><td><select class ='select'>" + select + "</select></td></tr>";
if($(".table").html().length <= 0)
{
$('.table').append($("<table>")).append(tableheader).append(tr);
}else{
if($(".table").html().length > 0){
$(".table").append(tr)
}
}
},
maxHeight:100,
width:600
});
thanks for your help
Why use object if you use only value?
if you realy don't need key juste create an array :
var selectValues = ["2", "1", "..."];
var value;
var select = selectValues.forEach(function(value){
$('.select').append($('<option>', {value: value}).text(value));
// <option value='volvo>Volvo</option>
});
// or if you want more compatibility
for (var i = 0, len = selectValue.length; i < len; i++) {
value = selectValue[i];
$('.select').append($('<option>', {value: value}).text(value));
});
Edit:
i make some mistake sorry.
first forEach will return nothing so it's can't work.
I test with your fidle. try this (replace by old for loop if you don't want to use map).
var select = selectValues.map(function(value){
return "<option value=" + value + ">" + value + "</option>";
// <option value='volvo>Volvo</option>
}).join('');
first you do not have to append from $('.select') because this dom not exist at this moment
and you can't concate an array in a string like this.
I have a select field and a button:
<select id="mylist"></select>
<input type="button" id="btn" value="update">
my js code:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();// GET_LIST() returns a array of strings which is the option texts.
//How to use optionList to update the options in <select> ?
});
How to update my options list with optionList in select tag ?
EDIT: Based on note from #amsutil alternate using html:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();
var select = $("#mylist");
select.html("");
var optionsHTML = "";
$.each(optionList, function(a, b){
optionsHTML += "<option>" + b + "</option>";
});
select.html(optionsHTML);
});
Try this:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();
var select = $("#mylist");
select.empty();
$.each(optionList, function(a, b){
select.append("<option>" + b + "</option>");
});
});
If you are wanting to create select options from an array, your values and label text will match. These will need to be stored in an object if you want to have values and text be different:
var btn = $('#btn');
btn.click(function() {
var optionList = GET_LIST();
var element = $('#mylist');
$.each(optionList, function(index, value) {
element.append('<option value="' + value + '">' + value + '</option>');
});
});
I see a few answers using 'append', but this creates too many DOM manipulations. If you have a large number of values in your array, it could slow the site down. It's much better to store all of the new options in a string, and do one DOM manipulation at the end.
Demo: http://jsbin.com/ubotu4/
Using $.map() to convert an array of strings into an array of option elements:
var optionList = GET_LIST();
var options = $.map(optionList, function (item, i) {
return $('<option>', {text: item}); // Convert string into <option>
});
$('#mylist').empty().append(options); // Append to the <select>