I have found several links to populate a dropdown list with an array but none of them work for me. Some links I have tried include:
This similar Stack Overflow question:
JavaScript - populate drop down list with array
This similar situation:
Javascript:
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
and the HTML:
<select id="CuisineList"></select>
But nothing is working. My goal is to populate a dropdown list from an external javascript array with values 0 to 255 so they can be used to come up with an RGB scheme. This is similar to the question that has been linked, but the linked question does not work when I copy and paste it into my text editor and preview it in Chrome.
try this:
i think your dom not ready when script executed
function ready() {
var cuisines = ["Chinese","Indian"];
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}
}
document.addEventListener("DOMContentLoaded", ready);
<select id="CuisineList"></select>
try this
var cuisines = ["Chinese","Indian"];
var innerData = '';
for(var i = 0; i < cuisines.length; i++) {
innerData += '<option value="' + 'cuisines[i]' + '">' + 'cuisines[i]' + '</option>';
}
document.getElementById('CuisineList').innerHTML = innerData;
Related
I have a dropdown that's populated through a loop. The selected attribute should be added when <%if o.getNextPage()%> is equal to i.
<select id="dropDown" onchange="display(this.value)">
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
options += "<option>" + i + "</option>";
}
document.getElementById("dropDown").innerHTML = options;
function display(e) {
document.getElementById("hidden").value = e;
document.invoiceForm.submit();
}
You can add value attribute to the option tag.
As suggested by #3Dos in comments you can use ‘document.createElement‘ without needing to insert raw HTML like this:
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
document.getElementById('dropDown').appendChild(opt);
}
This is the proper way of generating your dropdown list and preserve performance as you interact with the DOM only once thanks to the documentFragment
// These were not provided by OP but added to actually get this snippet running
var noOfPages = 5;
var start = 1;
var end = noOfPages;
var options = document.createDocumentFragment();
for (var i = start; i <= end; i++) {
var option = document.createElement('option');
option.value = i;
option.textContent = i;
options.appendChild(option);
}
document.getElementById("dropDown").appendChild(options);
<select id="dropDown" onchange="display(this.value)"></select>
I omitted the display function which is irrelevant as it refers to unprovided code.
Some of the web portals that I maintain use document.createElement to create options in a dropdownlist at runtime. All was well till IE10 but in IE11 or Edge suddenly the performance has gone down dramatically.
I have created a Fiddle: https://jsfiddle.net/nitinph/ej5p65um/
Please run it using both the sets of browsers (IE11/Edge and Chrome/Firefox). You will notice that IE11/Edge takes 10+ seconds whereas Chrome/Firefox takes less than a second.
My question is that is there any alternate way for using document.createElement so that performance is similar in IE11/Edge.
var pTime = document.getElementById("pTime");
var d = new Date();
var n = d.getTime();
var ddl = document.getElementById("TestDDL");
for (var i = 0; i < 5000; i++) {
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
ddl.options.add(opt);
}
d = new Date();
var n1 = d.getTime();
pTime.innerHTML = 'Time: ' + (n1 - n) / 1000 + ' sec.';
<select id="TestDDL">
</select>
<p id="pTime">
</p>
Update: Courtesy #Squint, here are the four alternatives to achieve performance in IE11/Edge:
var ddl = document.getElementById("TestDDL");
console.time("html")
var s = ""
for (var i = 0; i < 5000; i++) {
s += "<option value='" + i + '>' + i + "</option>"
}
ddl.innerHTML = s;
console.timeEnd("html")
clearContent()
console.time("insertAdjacentHTML")
for (var i = 0; i < 5000; i++) {
ddl.insertAdjacentHTML("beforeend", "<option value='" + i + '>' + i + "</option>")
}
console.timeEnd("insertAdjacentHTML")
clearContent()
console.time("frag")
var frag = document.createDocumentFragment();
for (var i = 0; i < 5000; i++) {
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
frag.appendChild(opt);
}
ddl.appendChild(frag);
console.timeEnd("frag")
clearContent()
console.time("direct add")
for (var i = 0; i < 5000; i++) {
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
ddl.options.add(opt);
}
console.timeEnd("direct add")
function clearContent() {
while (ddl.firstChild) {
ddl.removeChild(ddl.firstChild)
}
}
clearContent()
console.time("direct append")
for (var i = 0; i < 5000; i++) {
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
ddl.appendChild(opt);
}
console.timeEnd("direct append")
function clearContent() {
while (ddl.firstChild) {
ddl.removeChild(ddl.firstChild)
}
}
<select id="TestDDL">
</select>
<p id="pTime">
</p>
You could construct the element HTML with strings:
var optionList = ["foo", "bar", "baz"];
var elementHTML = "";
for (var index = 0; index < optionList.length; index++) {
elementHTML += "<option>" + optionList[index] + "</option>";
}
Then create the element and set the innerHTML
var element = document.createElement("select");
element.innerHTML = elementHTML;
This usually offers much better performance as you only call document.createElement() once. Direct dynamic DOM processing, sadly, is usually pretty slow and is recommended against.
I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!
I'm feeling my way around using JavaScript to populate a HTML5 page - ultimately to link into a Delphi / Datasnap page.
On my page I have a tag setup to provide a listbox as below:
<select id="FirmList" size="10"></select>
I then have a JavaScript script linked to a button that fires on the OnClick
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
The above seems to work - in that Chrome reports no errors and loops through 10 times. However nothing appears in the listbox on the web page, and the length property of sel.option does not increment
I've tried to use other options such as addressing sel.opt directly with no luck
Any suggestions?
You need to use .append()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
Use
sel.append(opt);
instead of
sel.add(opt);
DEMO
The reason it doesn't work is because sel is a jQuery object, and you're trying to use the native select.add() method, which only works on the native element.
The easy way to fix that would be to do what you seem to have to tried, use getElementById, but you've typed it wrong.
function getJobFirms() {
var sel = document.getElementById("FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.add(opt);
}
}
as you're already using jQuery, you could just do something like this
function getJobFirms() {
$("#FirmList").append(function() {
return $.map(' (. Y .) '.split(''), function(_,i) {
return $('<option />', {text : (i+1), value : i});
});
});
}
Use below jQuery script
function getJobFirms()
{
var sel = $("#FirmList");
//var sel = document.getElementByID("FirmList");
for (var i=0; i<10; i++) {
sel.append('<option value="'+i+'">'+(i+1)+'</option>');
}
}
Here is working JSFiddle
Since you're already using jQuery, you can use the following to make it more readable. As noted in the other questions, add is not a jQuery method and you need to use any variation of append.
function getJobFirms()
{
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
$('<option/>', {text: i + 1, value: i})
.appendTo(sel);
}
}
Demo
Use append();
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.text = i+1;
sel.append(opt);
}
OR DEMO JQUERY
var sel = $("#FirmList");
for (var i=0; i<10; i++) {
sel.append($('<option/>',{'text' : i+1},{"value":i}));
//OR
sel.append("<option value='"+i+"'>"+(i+1)+"</option>")
}
I want to create loop in select box. But I want one code for different select.
I am able create for one select but I want for multiple .
for single: with id
I want to change this code according class or for multiple select.
My code for this:
<select class="foo"></select><select class="foo"></select>
and:
$(document).ready(function() {
var elm = document.getElementByClass('foo'),
df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
elm.appendChild(df);
});
I think what you want is
document.getElementsByClassName('foo');
http://jsfiddle.net/5J29g/48/
Since you are using jQuery, so you could do like:
The demo.
$('.foo').each(function() {
for (var i = 0; i <= 60; i++) {
$('<option />').val(i).html('#option ' + i).appendTo($(this));
}
});
You can use class selector along with .append() and .clone()
$(document).ready(function () {
var df = document.createDocumentFragment();
for (var i = 0; i <= 60; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode(" " + i));
df.appendChild(option);
}
$('.foo').append(function () {
return $(df).clone()
})
});
Demo: Fiddle
I just updated your jsfiddle adding this:
(function() {
var foos=document.querySelectorAll(".foo");
for(var j=0;j<foos.length;j++){
var elm = foos[j],
df = document.createDocumentFragment();
for (var i = 1; i <= 42; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode("option #" + i));
df.appendChild(option);
}
elm.appendChild(df);
}
}());
sample check that out, DEMO
Try this:
$('.foo').each(function(){
// call your code create option element here with $(this).append()
});