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 want to list in second tag the models of the brand I selected. I need this for my homework. I do not know what to do. Please help me.
function notlariListele(param) {
var httpistegi = new XMLHttpRequest();
var adres = "https://raw.githubusercontent.com/atakanbalta/Moto-karsilastirma/master/markalar.json";
httpistegi.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
var list1 = document.querySelector("#slc1");
myArr.forEach(function(params) {
list1.innerHTML += '<option value="'+ params.marka +'">' + params.marka + '</option>';
});
}
};
httpistegi.open("GET", adres, true);
httpistegi.send();
}
notlariListele();
select {
width:100px;
height:20px;
}
<select id="slc1"></select>
<select id="slc2"></select>
You want to load populate two drop downs from the results of an HTTP request, where the value of the first drop down determines what options appear in the second. Your response looks something like this:
[
{
"marka": "BMW",
"modeller": [
"BMW 1000RR",
"R 1200 Rs",
...
]
},
{
"marka": "SUZUKI",
"modeller": [
"HAYABUSA",
"RAIDER",
...
]
},
...
]
Let's first simplify the question by ignoring the HTTP request, since it seems like you've got that part working. We can just hard code that result for now so we can focus on how the drop downs interact.
The key here is that when you change the value of the brand drop down, you need to re-populate the model drop down. You do this by listening to the change event of the brand drop down:
<select>.addEventListener("change", function(event) {
...
});
Then search for the brand the user is interested in by using the value that was selected. This can be done many in ways, but for this example, we'll use find:
var myItem = myArr.find(function(params){ return <some condition> });
Putting it together, we get something like this:
const jsonData = [{
"marka": "BMW",
"modeller": [
"BMW 1000RR",
"R 1200 Rs",
"S1000rr",
"K 1600B",
"K 1600Gtl",
"K 1600 gt",
"R 1200 rt",
"R 1200r",
"R 1200 Gs",
"F 750 GS",
"G 450 X",
"S 1000 XR"
]
},
{
"marka": "SUZUKI",
"modeller": [
"HAYABUSA",
"RAIDER",
"GSX 1000R",
"Gsx r1000 abs",
"V-strom 1000",
"V-strom 650",
"Burgman 400z",
"Burgman650z",
"V-strom 250"
]
},
];
const brandList = document.getElementById("brandList");
const modelList = document.getElementById("modelList");
function populateBrandList() {
brandList.innerHTML = '';
jsonData.forEach(function(params) {
brandList.innerHTML += '<option value="' + params.marka + '">' + params.marka + '</option>';
});
}
function populateModelList(brand) {
var brandInfo = jsonData.find(function(params){ return params.marka === brand });
if (brandInfo) {
modelList.innerHTML = '';
brandInfo.modeller.forEach(function(params) {
modelList.innerHTML += '<option value="' + params + '">' + params + '</option>';
});
}
}
brandList.addEventListener("change", function(event) {
populateModelList(event.target.value);
});
populateBrandList();
<select id="brandList"></select>
<select id="modelList"></select>
There are a couple of things to consider:
As your list of models are nested at the same level as the maker in the JSON object, you can use the index of that object to more efficiently find the list of models of a selected maker. That means that instead of having the value of <option> as your maker, you would use the index in the array. For this you will have to add the index parameter to your forEach: myArr.forEach(params, index)
For showing the relevant models when one item is selected, you will need to make use of the onchange JavaScript event, but also trigger this event at the start of page when list1 is preselected with the first value.
For cleaner code, you will need to have access to myArr, list1 and supposedly list2 from a higher scope, so you will have to declare them outside your onreadystatechange event handler.
Having all the above considered, try to think how you could achieve this with the aid of the referenced links. Once you got it (or at least attempted), look at the code snippet below on how this could be achieved. Remember that there is no one unique way of resolving this issue but there are always better ways than others – this one should do pretty well by keeping coherence in your code.
function notlariListele(param) {
var httpistegi = new XMLHttpRequest();
var adres = "https://raw.githubusercontent.com/atakanbalta/Moto-karsilastirma/master/markalar.json";
var myArr; // Store array here so that it is accessible in both functions
var list1 = document.querySelector("#slc1");
var list2 = document.querySelector("#slc2");
list1.onchange = function() {
// Empty second list first
list2.innerHTML = '';
myArr[this.value].modeller.forEach(function(model) {
list2.innerHTML += '<option value="' + model + '">' + model + '</option>';
});
}
httpistegi.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myArr = JSON.parse(this.responseText);
myArr.forEach(function(params, index) {
list1.innerHTML += '<option value="' + index + '">' + params.marka + '</option>';
});
list1.onchange(); // Trigger once to populate list at first.
}
};
httpistegi.open("GET", adres, true);
httpistegi.send();
}
notlariListele();
select {
width: 100px;
height: 20px;
}
<select id="slc1"></select>
<select id="slc2"></select>
I have a list of objects coming into my web page. One property of the object is firstName. I display some of the properties and have a clickable one that calls another fuction. I want to pass the object from the array to the second function
jQuery.each(x, function () {
$('#results').append("<a href='javascript:void(0)' onClick='workSup(" + '"' + $(this) + '"' + ")' >" + decodeURI(this.firstName) + ' ' + decodeURI(this.lastName) + " - " + decodeURI(this.preApprovalSupervisorName) + " <a/><br/> ");
});
function workSup(x) {
alert(x.firstName);
}
I've tried passing this as well as $(this). The alert reads "undefined"
What am I doing wrong? Thanks!
jQuery has a great function, .data(), I'd recommend you look into:
$('#selector').data("key", "value (string, number, object, etc.)")
$('#selector').data("key"); //Returns the data, or null if not yet set
Also, I highly recommend moving away from onclick to
$('.myClassName').on("eventName (such as click, change or keyup)", "jqSelector", handlerFunction);
var x = [{firstName:"John", lastName:"Lennon"}, {firstName:"Phil", lastName:"Ochs"}]
$(document).ready(function() {
jQuery.each(x, function () {
var linkEl = $('<a class="myLink" href="javascript:void(0)">' + this.firstName + " " + this.lastName + '</a>');
linkEl.data("myObjData", this);
$('#results').append(linkEl);
});
$(document).on("click", ".myLink", function() {
var myObjData = $(this).data("myObjData");
//myObjData.firstName can be accessed here
alert(JSON.stringify(myObjData));
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="results"></div>
</body>
</html>
$('.myClass').on() is even better than $('.myClass').click() because it will even listen to elements that are dynamically added later
jQuery.each(x, function() {
//create the a element
var $a = $("<a href='javascript:void(0)'>"+
decodeURI(this.firstName) +' '+ decodeURI(this.lastName) +
" - "+ decodeURI(this.preApprovalSupervisorName) +
"</a><br/>");
//bind the event handler to it
$a.on('click', function(){
workSup(x);
});
});
As mentioned by #taplar you're creating inline binding. Basically what happens is that your $(this) gets resolved as string and later inside your workSup() method you're trying to access firstName property of the string which is obviously undefined.
What you have to do instead is to dynamically create your link and attach event listener to it (in which you call the workSup() method) like so:
// Your data
const x = [
{ firstName: 'First', lastName: 'Last', preApprovalSupervisorName: 'Super' },
{ firstName: 'Another', lastName: 'One', preApprovalSupervisorName: 'His super' },
];
// Your workSup method
const workSup = x => alert(x.firstName);
// Loop though each item
$.each(x, function() {
// Create new <a> element
const $element = $('<a></a>')
// Add href attribute
.attr('href', 'javascript:void(0)')
// Set its text
.text(`${decodeURI(this.firstName)} ${decodeURI(this.lastName)} ${decodeURI(this.preApprovalSupervisorName)}`)
// Attach onClick listener
.on('click', () => workSup(this));
// Append the element to the results and add line break
$('#results')
.append($element)
.append('<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
var x =[{firstName: "John", lastName:"DG", preApprovalSupervisorName: "sup"}];
jQuery.each(x, function (index, value) {
$('#results').append(
$("<a>")
.attr("href","#")
.html( decodeURI(value.firstName) + ' ' + decodeURI(value.lastName) + " - " + decodeURI(value.preApprovalSupervisorName))
.click(function(){
workSup(value);
})
);
});
function workSup(x) {
alert(x.firstName);
}
I have this code:
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
'<div>' + v.points + '</div>' +
'<div>' + v.other + '</div>' +
'</a>'
);
});
Into the user grid div, I append the string with the values taken from data.
v.points and v.other are the numbers.
To this moment, everything works just fine. But what I need is to embed the for loop into the divs. In the places where I have v.points and v.other I want to put two simular FOR loops.
for(var i = 0; i < v.points; i++) {
//here is the html line that should be passed to the div, where v.points are now
<div>This is the point</div>
}
And almost the same for the v.other. Only with another line that should be pasted.
So basically how can I do that? I was trying to paste this loops right inside the "append()" but that didn't work out. I was also trying to create a variable inside of the loop and pass it in to the append, but got only one result, instead of all that I have needed.
I'm not sure if this is what are you looking for, this code prints 5 "This is your point" and 3 "This is your other" inside the anchor.
var data = [
{
points: 5,
other: 3
}
]
function printPoints(vPoints){
var str = "";
for(var i=0; i<vPoints; i++) {
str+="<div>"+"This is your point"+"</div>";
}
return str;
}
function printOther(vOther){
var str = "";
for(var i=0; i<vOther; i++) {
str+="<div>"+"This is your other"+"</div>";
}
return str;
}
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
printPoints(v.points)+
printOther(v.other)+
'</a>'
);
});
See it on action here
I have a created dynamic search that takes data from an input form and searches through an array of objects for matches. These matches (if they exist) are displayed on one line of a result along with a 'button' to click to take action on that specific search result line.
Each object in the array corresponds to a line of the result assuming that the search term if found in that object.
I have created a delegated listener to listen for clicks on the button for each shown result line. How do I get the button to act on the the 'index: number' contained in the object that created that line of the results.
My code so far is an follows:
var multiArr = [
{label: "Asap Rocky", song: "National", index: 0},
{label: "Rihanna", song: "Umbrella", index: 1},
{label: "Coldplay", song: "Paradise", index: 2}];
$('#results').on("click", ".result-button", function(event) {
alert("You clicked:" + event.target.nodeName);
console.dir($(this).text);
});
$("#finder").keyup(function(e){
var q = $("#finder").val();
console.log("Search Bar contents: " + q);
var pattern = new RegExp( "^" + q, "i");
$("#results").empty();
for (var i = 0; i < multiArr.length; i++){
console.log("Checking for " + q + " in " + multiArr[i].label);
console.log("The above is " + pattern.test(multiArr[i].label));
if (pattern.test(multiArr[i].label)) {
console.log("something in here beings with " + q);
/*console.log("Img Url: " + thaArr);*/
//do something
$("#results").append("<div class='result-line'><div class='result-img'><img src='http://img.youtube.com/vi/36wDeLKKoXE/default.jpg' class='center-result-img'></div><div class='result-song-info'><div class='result-song-title'><p>" + multiArr[i].song + "</p></div><div class='result-song-artist'><p>" + multiArr[i].label + "</p></div></div><div class='result-button'>>></div></div>");
}
}
});
A simple solution would be to first attach a data attribute to the result-button itself and then fetch that data on your click callback, where the data you are attaching is the index value of your element.
In order words, you would add to the result-button div where you append to #results, that is, this:
"<div class='result-button'>"
the following data attribute:
"<div class='result-button' data-id='" + multiArr[i].index + "'>"
Then, in your click call back, you can simply get that id by using this:
$(this).data("id")
Now, just in case this doesn't make total since, I decided to help you out a little bit more by improving your code some. The main improvement I made is that my example doesn't re-create the html on each filter change. Instead, all of the data is appended to the page at the start, and then it is either hidden or shown depending on the label text. Additionally, I changed the way you are building up the elements to make it easier to edit in the future.
JSFiddle: http://jsfiddle.net/seibert_cody/j4rqdh8L/
HTML:
<input id="finder" type="text">
<div id="results"></div>
JS:
$(document).ready(function(){
// Set up the test data
var multiArr = [
{
label: "Asap Rocky",
song: "National",
index: 0
},
{
label: "Rihanna",
song: "Umbrella",
index: 1
},
{
label: "Coldplay",
song: "Paradise",
index: 2
}
];
// Append it all to the #results page initially
for (var i = 0; i < multiArr.length; i++){
$("#results").append(
$("<div class='result-line'></div>").append(
$("<div class='result-img'></div>").append(
$("<img src='http://img.youtube.com/vi/36wDeLKKoXE/default.jpg' class='center-result-img'>")
).append(
$("<div class='result-song-info'></div>").append(
$("<div class='result-song-title'></div>").append(
$("<p>" + multiArr[i].song + "</p>")
)
)
).append(
$("<div class='result-song-artist'></div>").append(
$("<p>" + multiArr[i].label + "</p>")
)
).append(
$("<div class='result-button' data-id='" + multiArr[i].index + "'>Play</div>")
)
)
);
}
// Clicked on the play button
$('#results').on("click", ".result-button", function(event){
console.log($(this).data("id"));
});
// Only show the labels matching filter
$("#finder").keyup(function(e){
var q = $("#finder").val();
var pattern = new RegExp( "^" + q, "i");
$("#results").children().each(function(child){
var label = $(this).find(".result-song-artist p").html();
if (pattern.test(label)){
$(this).show();
}else{
$(this).hide();
}
});
});
});