Adding options to select with javascript
You could achieve this with a simple for
loop:
var min = 12,
max = 100,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
JS Fiddle demo.
JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
Edited in response to comment from OP:
[How] do [I] apply this to more than one element?
function populateSelect(target, min, max){
if (!target){
return false;
}
else {
var min = min || 0,
max = max || min + 100;
select = document.getElementById(target);
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);
// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');
// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);
JS Fiddle demo.
And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement
in order to chain the populate()
function, as a method, to the DOM node:
HTMLSelectElement.prototype.populate = function (opts) {
var settings = {};
settings.min = 0;
settings.max = settings.min + 100;
for (var userOpt in opts) {
if (opts.hasOwnProperty(userOpt)) {
settings[userOpt] = opts[userOpt];
}
}
for (var i = settings.min; i <= settings.max; i++) {
this.appendChild(new Option(i, i));
}
};
document.getElementById('selectElementId').populate({
'min': 12,
'max': 40
});
JS Fiddle demo.
References:
node.appendChild()
.document.getElementById()
.element.innerHTML
.
How to add Drop-Down list (select) programmatically?
This will work (pure JS, appending to a div of id myDiv
):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body;
//Create array of options to be addedvar array = ["Volvo","Saab","Mercades","Audi"];
//Create and append select listvar selectList = document.createElement("select");selectList.id = "mySelect";myParent.appendChild(selectList);
//Create and append the optionsfor (var i = 0; i < array.length; i++) { var option = document.createElement("option"); option.value = array[i]; option.text = array[i]; selectList.appendChild(option);}
Adding options to an html select element
document.createElement("option").text="User1"
returns "User1"
, the result of the assignment, not a HTMLOptionElement
. You should code:
var newoption = document.createElement("option");
newoption.text = "User1";
selector.add(newoption);
edit: OP is using .add()
method for adding an option
to the select
element. HTMLSelectElement
object does have .add()
method.
Adding options to multiple Select elements
Uncaught TypeError: Failed to execute 'add' on 'HTMLOptionsCollection': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'
The error message suggests you add a value that's either a HTMLOptionElement
or a HTMLOptGroupElement
. So, you can write a function that creates such an element :
function createOption(option, label) {
var option = document.createElement("option");
option.setAttribute("value", option);
option.innerHTML = label;
return option;
}
And call it in your selections[i].options.add
function.
function buildDropDowns(sizes) { var selections = document.getElementsByClassName('resourceSize'); for(var i=0; i<selections.length; i++) { //console.log(selection); for(var j= 0; j<sizes.length; j++) { selections[i].options.add(createOption(sizes[j], sizes[j])); } }}
function createOption(option, label) { var option = document.createElement("option"); option.setAttribute("value", option); option.innerHTML = label; return option;} var sizes = ["XXL", "XL", "L", "M", "S", "XS"];
buildDropDowns(sizes);
<select id="busMerchPlan" name="busMerchPlan" class="resourceSize"></select><select id="busMerchAlloc" name="busMerchAlloc" class="resourceSize"></select><select id="busMerchBuy" name="busMerchBuy" class="resourceSize"></select><select id="busMerchPDD" name="busMerchPDD" class="resourceSize"></select>
Adding options to a select using jQuery?
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);
how to dynamically add options to an existing select in vanilla javascript
This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript
Basically:
daySelect = document.getElementById('daySelect');
daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');
Add option to select box
function myFunction()
{
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = document.getElementById("text").value;
x.add(option);
}
body, button{
font-family: consolas, sans-serif;
}
h1,h2,h3{
border-bottom: 2px solid black;
}
<h1>Add Options!</h1>
<mark>Sorry, but your question was not clear enough and I could not fully understand it. Here is my best shot at answering the question.</mark>
<h2> Result </h2>
<textarea placeholder = "Type here" id = "text"></textarea>
<input type = "submit" onclick = "myFunction()">
<br>
<select id = "mySelect">
</select>
HTML Select Option : How to Add Another Line of Option
select = document.getElementById('selectElementId');
var opt = document.createElement('option');
opt.value = 4;
opt.innerHTML = 4;
select.appendChild(opt);
You can do it in a loop as well:
http://jsfiddle.net/wdmz3cdv/
var min = 4,
max = 5,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
What is the best way to add options to a select from a JavaScript object with jQuery?
The same as other answers, in a jQuery fashion:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});
Adding another option when the select dropdown is clicked?
I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).
Consider:
...
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var $statusButton = $(".statusButton");
if(k == 1){
if(value == "Disable")
{
$statusButton.append("<option value='Disable' >Disable</option>");
}
else if(value == "Enable")
{
$statusButton.append("<option value='Enable' >Enable</option>")
}
...
If you do things that way, you don't have to mess around with any extra .html
calls.
Related Topics
How to Move an Element into Another Element
Make Iframe Automatically Adjust Height According to the Contents Without Using Scrollbar
Link Index.Html Client.Js and Server.Js
How to Get a File or Blob from an Object Url
Onchange Event on Input Type=Range Is Not Triggering in Firefox While Dragging
Make a Link Use Post Instead of Get
Get Page Generated With JavaScript in Python
Transfer Data from One HTML File to Another
What Are Data-* HTML Attributes
Difference Between Client-Side and Server-side Programming
JavaScript Function Doesn't Work When Link Is Clicked
Invoking JavaScript Code in an Iframe from the Parent Page
How to Store an Array in Localstorage
Submit Form Without Page Reloading
Which "Href" Value Should I Use For JavaScript Links, "#" or "JavaScript:Void(0)"