Add item to dropdown list in HTML using JavaScript - 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

Related

Populating Select with 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 :)

Fill options of select tag

In my HTML file I have a select tag in which when I select the first one, another select tag should fill out with some options, and when select the other option, some others options will fill out in the other select tag.
I did that in my HTML :
<script type="text/javascript">
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel'); selectTag.options.length = 0; // wireless should
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value= 'auto';
auto.innerHTML = 'auto';
if (document.getElementById('country').selected="1") {
for(index=4920; index<=5825; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if(document.getElementById('country').selected="2"){
for(index=4920; index<=6075; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
}
}
</script>
The wirelessChanne is the select tag must fill.
The country tag is in the if statement and the selected one is our condition.
Now when I run the code, the second if does not work.( It does not display till 6075 in the second statement ) and also does not add auto option to the select tag.( I want to display auto in the first option of the wirelessChannel without conditions, I mean at the first index it should be displayed auto)
Where I am doing wrong?
to test if a value is equal to something you need to use a double equal sign - to set a value to something you would use a single equal sign.
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel');
selectTag.options.length = 0;
var auto = document.createElement('option');
auto.value= 'auto';
auto.text = 'auto';
selectTag.appendChild( auto );
var oCountry=document.getElementById('country');
if ( oCountry.value==1 ) {
for( index=4920; index <= 5825; index+=5 ){
var opt = document.createElement('option');
opt.value= index;
opt.text = index;
selectTag.appendChild( opt );
}
} else if( oCountry.value=='2' ){
for( index=4920; index <= 6075; index+=5 ){
var opt = document.createElement('option');
opt.value= index;
opt.text = index;
selectTag.appendChild( opt );
}
}
}
In the If statement Use == instead of =. For adding an option auto to the select append that before your for loop.You have created the option but forgot to append the option.Use selectTag.appendChild(auto); befor the for loop
fillWirelessChannel();
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel'); selectTag.options.length = 0; /* wireless should */
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value= 'auto';
auto.innerHTML = 'auto';
selectTag.appendChild(auto);
console.log(document.getElementById('country').value);
if (document.getElementById('country').value=="1") {
for(index=4920; index<=5825; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if(document.getElementById('country').value=="2"){
for(index=4920; index<=6075; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
}
}
<select id="wirelessChannel">
</select>
<select id="country" onchange="fillWirelessChannel()">
<option value="1">1</option>
<option value="2">2</option>
</select>

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>

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

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);
}

Categories

Resources