Populating Select with Javascript - javascript

I'm trying to populate select options with results from a for cycle but I just can't get it to work. I call the function from the select's onclick but it just doesn't work.
Here's a working JS fiddle without the function but I need it to be in a function.
http://jsfiddle.net/t8fdh/610/
And here's what I'm trying to get to work.
http://jsfiddle.net/t8fdh/612/
function populate() {
var max = new Date().getFullYear() + 1,
min = max - 9,
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);
}
};
<select id="selectElementId" onload="populate()"></select>

Why using onload on the select element, try adding the execution of populate() function on the window load using window.onload = populate();
window.onload = populate();
function populate() {
var max = new Date().getFullYear() +1;
var min = max - 9;
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);
}
};
<select id="selectElementId" ></select>

It works if you use document.onload();
jsfiddle:
http://jsfiddle.net/t8fdh/616/

According to https://www.w3schools.com/tags/ev_onload.asp, you can only use onload on the following tags:
<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style>
You can put your onload on the body tag and it will work :)

Related

Can`t fill select with options

I just want to fill select with array values.
Here is js code (which I took from here). It doesn't work even without loop. So if I could make it work, then filling with array won`t be a problem.
var sel = document.getElementById('CountrySelect');
var opt = document.createElement('option');
opt.innerHTML = "CountyNumerOne";
opt.value = 0;
sel.appendChild(opt);
<select id="CountrySelect">
</select>
But on the output I get empty list
You must ensure the script is triggered after the select element is parsed by the browser. You can do this either by putting the script tag after your select element, or listening for the document loaded event in your script:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var sel = document.getElementById('CountrySelect');
var opt = document.createElement('option');
opt.innerHTML = "CountyNumerOne";
opt.value = 0;
sel.appendChild(opt);
});
</script>
var select = document.getElementById("CountrySelect");
var options = ["1", "2", "3", "4", "5"]; //array
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}​
http://jsfiddle.net/yYW89/

Creating a dropdown list with hyperlinked items in an array

I'm very new to JS, so forgive the simplicity of this question... Trying to create a dropdown list with hyperlinked items using an array. The end product will have hundreds of entries, so it's important to save space.
Two things to keep in mind: I can't use JQuery and I have to integrate this in WordPress.
I know I'm doing this incorrectly, but the below code should give an accurate idea of what I'm trying to do. Any help much appreciated.
<body>
<form id="siteList">
<select id="selectSite">
<option>Choose a site</option>
</select>
</form>
</body>
</script>
var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");
var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");
// Get dropdown element from DOM
var dropdown = document.getElementById("selectSite")
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
// Append the element to the end of Array list
dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
}
</script>
http://jsfiddle.net/L2awjmvd/
You have to write the code like below:
<script type="text/javascript">
function createarray() {
var myArray = new Array("Google", "Yahoo", "Bing", "Gmail", "Facebook");
var links = new Array("http://www.google.com", "http://www.yahoo.com", "http://www.bing.com", "http://www.gmail.com", "http://www.facebook.com");
var dropdown = document.getElementById("selectSite");
for (var i = 0; i < myArray.length; ++i) {
var option = document.createElement("option");
option.text = myArray[i];
option.value = links[i];
dropdown.add(option);
// dropdown[dropdown.length] = new Option(myArray[i].link(links[i]), myArray[i].link(links[i]));
}
}
function selectSiteRedirect(selectedSite) {
window.location.href = selectedSite;
}
</script>
<body onload="createarray();">
<form id="siteList">
<select id="selectSite" onchange="selectSiteRedirect(this.value);">
<option>Choose a site</option>
</select>
</form>
</body>
I think this is the correct way to do it:
<script>
var my_array = ["Google", "Yahoo", "Bing"];
var my_array_links = ["www.google.com", "www.yahoo.com", "www.bing.com"];
var select = document.getElementById("selectSite");
for (i = 0; i < my_array.length; i++) {
var opt = document.createElement('option');
opt.value = my_array[i];
opt.innerHTML = my_array_links[i];
select.appendChild(opt);
}
</script>
Here is http://jsfiddle.net/fvjeunbu/
If you want to redirect when the user select an option, then the select declaration should be:
<select id="selectSite" onchange="javascript: window.location.assign(this.value);">
<script>
function pageLoad() {
var my_array = ["Google", "Yahoo", "Bing"];
var my_array_links = ["www.google.com", "www.yahoo.com", "www.bing.com"];
var select = document.getElementById("selectSite");
for (i = 0; i < my_array.length; i++) {
var opt = document.createElement('option');
opt.value = my_array_links[i];
opt.innerHTML = my_array[i];
select.appendChild(opt);
}
}
window.onload = pageLoad;
function selectSiteRedirect(selectedSite) {
// window.location.href = selectedSite;
if(selectedSite!="selected")
window.open(selectedSite, '_blank');
}
</script>
<div>
<select id="selectSite" onchange="selectSiteRedirect(this.value)">
<option selected="selected" value="selected">Choose a site</option>
</select>
</div>

Auto populate option tag not working java script

I'm trying to populate number in select - option tag .But my script fills number at only one select tag
HTML :
<div class="form_row">
<label>Week Num</label>
<select class="form_select1" id="weeknum"></select>
<b class="bold1">&nbsp TO &nbsp</b>
<select class="form_select1" id="weeknum1"></select>
</div>
Javascript :
<script>
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
select1.add(option, 0);
}
</script>
How do i achieve that ?
You can add an element only once to a parent node, so you need to create another option element:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}
Here's the JSFIddle.
Try this ...
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option1, 0);
var option2 = document.createElement('option');
option2.text = option2.value = i;
select1.add(option2, 0);
... creating a distinct "option" for each select list. The created elements cannot be reused.
You need to create a distinct option element for each list. A given DOM element can only be in one place in the DOM.
edit: I see it's already answered... well, my first answer :)
try this:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
var option1 = document.createElement('option');
option.text = option.value = option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}

javascript does not recognize my html elements

What I get is a blank page, although I should have a combo box. The array gets filled just fine - I alerted some values and it works, but the combo box does not show anything.
What I want to do is create a combobox from the data retrieved from the array, but it doesn't seem to work.
<script type="text/javascript">
var array = {"ADDRESS_ID":["3","5"],"ADDRESS_PLACE":["a","b"],"ADDRESS_PARENT":[null,null],"TYPE":["0","1"]};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function () {
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = array.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>
<div id="container_for_select_container">
</div>
</body>
</html>
Your code works fine apart from a few things. As mentioned the length of your Array is wrong. You need to have the array['ADDRESS_ID'].length instead of array.length and you need to either place the div with id 'container_for_select_container' before you JavaScript code or place your JavaScript code in a window.load function. Otherwise you are trying to append your select box to a HTML element that does not yet exist.
<div id="container_for_select_container"></div>
<script type="text/javascript">
var array = {
"ADDRESS_ID": ["3", "5"],
"ADDRESS_PLACE": ["a", "b"],
"ADDRESS_PARENT": [null, null],
"TYPE": ["0", "1"]
};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function() {
alert('You selected option ' + this.selectedIndex);
};
// Add some <option>s
numOptions = array['ADDRESS_ID'].length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);
</script>
The problem seems to be with your numOptions. Shouldn't it be:
numOptions = array['ADDRESS_ID'].length;
instead of
numOptions = array.length;?
Here's the working fiddle
You need to change your numOptions variable to:
numOptions = array['ADDRESS_ID'].length;
Working example in JSFiddle:
http://jsfiddle.net/reBSB/
New Code:
var array = {"ADDRESS_ID":["3","5"],"ADDRESS_PLACE":["a","b"],"ADDRESS_PARENT":[null,null],"TYPE":["0","1"]};
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theContainer = document.createElement('div');
theContainer.id = array['TYPE'][0];
theSelect = document.createElement('select');
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.onchange = function () {
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = array['ADDRESS_ID'].length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = array['ADDRESS_ID'][i];
anOption.innerHTML = array['ADDRESS_ID'][i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

Categories

Resources