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.
Related
I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();
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 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;
I have 'button' like this
<span data-id="dr21" data-minheight="100" data-maxheight="200" data-minwidth="20" data-maxwidth="50" class="customsizebutton">(edit size)/span>
and script like this
<script>
$('.customsizebutton').click(function ()
{
var id = $(this).data('id');
var minHeight = $(this).data('minheight');
var maxHeight = $(this).data('maxheight');
var minWidth = $(this).data('minwidth');
var maxWidth = $(this).data('maxwidth');
var arrayH = [];
var arrayW = [];
for (var i = minHeight; i <= maxHeight-1; i++) {
arrayH.push(i);
}
for (var i = minWidth; i <= maxWidth-1; i++) {
arrayW.push(i);
}
var selectListH = document.getElementById("h-"+id);
for (var i = 0; i < arrayH.length; i++) {
var option = document.createElement("option");
option.text = arrayH[i];
selectListH.appendChild(option);
}
var selectListW = document.getElementById("w-"+id);
for (var i = 0; i < arrayW.length; i++) {
var option = document.createElement("option");
option.text = arrayW[i];
selectListW.appendChild(option);
}})
</script>
I am trying to fill the two dropdowns with
<option>200</option>
<option>199</option>...
<option>101</option>
<option>100</option>
<option>50</option>
<option>49</option>...
<option>21</option>
<option>20</option>
It currently fills the dropdowns the opposite direction (low to high). I'm new to this and trial and error has got me this far.
Thanks
Just populate the arrays in reverse order.
for (var i = maxHeight-1; i >= minHeight; i--) {
arrayH.push(i);
}
for (var i = maxWidth-1; i >= minWidth; i--) {
arrayW.push(i);
}
If you merely need to populate your dropdowns in reverse order, you can just iterate them in reverse, like so:
for (var i = arrayH.length - 1; i >= 0; i--) {
var option = document.createElement("option");
option.text = arrayH[i];
selectListH.appendChild(option);
}
If you want to actually reverse the items in the array, as the title of your question denotes, that's even easier, with the Array.reverse function:
arrayH = arrayH.reverse();
If you're new, I recommend reviewing the JavaScript documentation over at Mozilla.
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()
});