HTML drop down menu using Javascript - javascript

Im trying to make a html drop down menu, using JavaScript that uses a loop to insert options starting from a particular year and stopping at the current year. But I have been unsuccessful, the drop down menu is appearing but it has nothing in in
<script language="JavaScript" type="text/javascript">
function Year()
{
var Year = 1986
var CurrentYear = new Date().getFullYear()
while( Year < CurrentYear){
{
Year++;
document.write("<option>" + Year + "</option>");
}
}
and here is the HTML
<select id='ddYear'>
<option selected disabled hidden label="Select An Option">
<script language="JavaScript" type="text/javascript">
Year();
</script>
</select>

You have an extra curly brace. I also would suggest a better naming:
function buildOptions() {
var year = 1986;
var currentYear = new Date().getFullYear();
while( year < currentYear) {
year++;
document.write("<option>" + year + "</option>");
}
}
and then the HTML:
<select id='ddYear'>
<option selected disabled hidden label="Select An Option">
<script language="JavaScript" type="text/javascript">
buildOptions();
</script>
</select>

You can add the following code inside while loop.
Year++;
var select = document.getElementById("ddYear");
var option = document.createElement('option');
option.text = option.value = Year;
select.add(option, 0);

your approach can be a little bit better in my humble opinion.
First of all, you can avoid using a script tag inside your html to call a function, because this can be done in your script directly.
In this working fiddle, by taking your HTML and javascript, we generate dates from 1986 INCLUDED until 2015 INCLUDED, in your previous script you were excluding these dates.
I've also added you a change event listener for future use, since you may want to know when the select dropdown is going to be changed.
Fiddle:
http://jsfiddle.net/briosheje/0Luq0fxf/
<-- Not needed if you want to run the snippet below.. However if you want to add some css / html for further immediate testing..
HTML :
<select id='ddYear'>
<option selected disabled hidden label="Select An Option">
</select>
Javascript:
var ddYear = document.getElementById('ddYear');
var y = 1986;
var currYear = new Date().getFullYear();
while ( y <= currYear ) {
var newOption = document.createElement('option');
newOption.text = newOption.value = y;
y++;
ddYear.add(newOption);
}
ddYear.addEventListener('change',function() {
alert(this.value);
});
Snippet:
var ddYear = document.getElementById('ddYear');
var y = 1986;
var currYear = new Date().getFullYear();
while ( y <= currYear ) {
var newOption = document.createElement('option');
newOption.text = newOption.value = y;
y++;
ddYear.add(newOption);
}
ddYear.addEventListener('change',function() {
alert(this.value);
});
<select id='ddYear'>
<option selected disabled hidden label="Select An Option">
</select>

Consider using jQuery instead of pure javascript. It will make your code much easier to read (i.e. avoid to insert a script element inside select code and allows you to update content runtime):
HTML
<select id='ddYear'>
<option selected disabled hidden label="Select An Option"></option>
</select>
Jquery
var startYear = 1986;
var currentYear = (new Date).getFullYear();
for(var year=startYear; year<currentYear; year++)
{
$('#ddYear').append($('<option/>', {
value: year,
text : year
}));
}
Fiddle

Related

How to populate dropdown list at selection element with values from Google sheet?

I have a Google sheet with custom HTML form. The form contains <selection> element.
Like this
<select id="category_name" name="category_name" class="control" style="width:150px;height:20px;margin:10px 0 10px 0;">
<option value="" selected></option>
</select>
I'm getting values from the sheet
function getCategory() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getSheetByName(SHEET_NAME);
let list = sh.getRange(2, 1, sh.getLastRow() - 1).getValues();
return list;
}
And then I'm populating this selection with expected values in HTML file
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("category_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.val = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getCategory();
}());
It looks like list was populated well, but when I choice some item from selection it returns blank value after form submitting.
Where I'm wrong and how to fix it?
Issue:
You are not setting the <option> value correctly: val is not a valid attribute. Because of this, no value is added to each <option> and they are not submitted.
Solution:
Set the option value like this:
option.value = selectList[i][0];
Using Option constructor:
Of course, using the Option constructor would also work:
var option = new Option(selectList[i][0], selectList[i][0]);
Reference:
HTMLOptionElement
Option()
I use this a lot:
function updateSelect(vA,id){
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);//Option(text, value);
}
}
new option

Javascript iteration with thymeleaf, how to pass index to array in thymeleaf

I'm setting 2 select in html, the second one depends of the first one, so I use a script "onchange", so when the first value of the select change, the second one change too, I don't know how to get the variable of my FOR to get the index of the thymeleaf model in my script
SCRIPT-
So my problem here it's inside the if when I tried to get the value of documentos[i].proyecto.id, but I can get documentos[0, 1 or any number].proyecto.id
/*<![CDATA[*/
function load(){
var e = document.getElementById("proyecto-id");
var value = e.options[e.selectedIndex].value;
var sub = document.getElementById("documento-id");
var length = sub.options.length;
for (z = 0; z < length; z++) {
sub.options[z] = null;
}
for(i=0;i<[[${#lists.size(documentos)}]];i++){
if([[${documentos[ i ].proyecto.id}]] == value){
var opt = document.createElement('option');
opt.value = [[${documentos[ i ].id}]]
opt.text = [[${documentos[ i ].nombre}]];
sub.add(opt);
}
}
}
/*]]>*/
HTML select
<select id="proyecto-id" class="custom-select" th:onchange="load()">
<option th:each="p : ${proyectos}"
th:text="${p.nombre}"
th:value="${p.id}">
</option>
</select>
<select id="documento-id" class="custom-select">
</select>

Change options in a drop-down list depending on another selected drop-down list

I'm trying to do this which you have a dropdown list and depending what you select, the next dropdown list will have different options.
I have my codes in jsfiddle
<!DOCTYPE html>
<html>
<body>
<select id="diffList" onchange="changeList()">
<option value="">-- Difficulty --</option>
<option value="1">Easy</option>
<option value="2">Medium</option>
<option value="3">Difficult</option>
</select>
<select id="numbList"></select>
<script>
var difficulty = {};
difficulty['1'] = [1,2,3];
difficulty['2'] = [4,5,6];
difficulty['3'] = [7,8,9];
function changeList() {
var diffList = document.getElementById("diffList");
var numbRange = document.getElementById("numbList");
var selectDiff = diffList.options[diffList.selectIndex].value;
while(numbRange.options.length)
{
numbRange.remove(0);
}
var diff = difficulty[selectDiff];
if(diff)
{
var i;
for(i = 0; i < diff.length; i++)
{
var difficulty = new Option(diff[i], i);
numbRange.options.add(difficulty);
}
}
}
</script>
</body>
</html>
The problem I'm encountering is the next droplist is not showing any options. I've look through my codes many times and I still can't seem to find out what's wrong with it. Would someone mind looking over it and let me know?
Thanks a lot.
Here is working code (tested only ib Chrome).
The one problem was here - for loop does not create nested scope in JS, so it shadowed global variable difficulty
for(i = 0; i < diff.length; i++) {
var difficulty = new Option(diff[i], i);
...
Ok, let's do it:
You should not use onchange="changeList()" on jsfiddle beause it wraps your code into the onclick handler and the changeList function does not visible from the outer scope.
You should use diffList.value for detect the currently selected value in the first selectbox: var selectDiff = diffList.value;
Do not name the new option variable difficulty - it overrides the difficulty variable from the outer scope. Name it option, for example: var option = new Option(diff[i], i);
Add the event listener for diffList from JS: diffList.addEventListener('change', changeList)
http://jsfiddle.net/h3hbovar/4/
I think the primary problem here was javascript scoping within functions. If difficulty is defined outside the context of the function, it needs to be defined as a global by being attached to window
<!DOCTYPE html>
<html>
<body>
<select id="diffList" onchange="changeList()">
<option value="">-- Difficulty --</option>
<option value="1">Easy</option>
<option value="2">Medium</option>
<option value="3">Difficult</option>
</select>
<select id="numbList"></select>
<script>
window.difficulty = {};
window.difficulty['1'] = [1,2,3];
window.difficulty['2'] = [4,5,6];
window.difficulty['3'] = [7,8,9];
function changeList() {
var diffList = document.getElementById("diffList");
var numbRange = document.getElementById("numbList");
var selectDiff = diffList.options[diffList.selectedIndex].value;
while(numbRange.options.length)
{
numbRange.remove(0);
}
var diff = window.difficulty[selectDiff];
if(diff)
{
var i;
for(i = 0; i < diff.length; i++)
{
var difficulty = new Option(diff[i], i);
numbRange.options.add(difficulty);
}
}
}
</script>
</body>
</html>

How can I generate a list of links based on dropdown menu choices?

So I've got a bunch of information for a bunch of different countries, and I'm trying to get it sorted like so:
Dropdown menu to choose a country -> Dropdown menu to choose information type -> here's a link to that information
I'm not so great with javascript, but I found this solution that allows me to change the content of the second dropdown based on the selection chosen from the first dropdown:
<script type="text/javascript">
function configureDropDownLists(ddl1, ddl2) {
var albania = new Array('History', 'Legal Guides');
var andorra = new Array('Country Overview', 'Demographics', 'Legal Guides');
switch (ddl1.value) {
case 'Albania':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < albania.length; i++) {
createOption(document.getElementById(ddl2), albania[i], albania[i]);
}
break;
case 'Andorra':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < andorra.length; i++) {
createOption(document.getElementById(ddl2), andorra[i], andorra[i]);
}
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
And then the dropdown boxes, in the HTML:
<select id="ddl" onchange="configureDropDownLists(this,'ddl2')">
<option value=""></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
</select>
<select id="ddl2">
</select>
So now I'm wondering how I can take that secondary choice and use it to generate a list of links for someone to choose from--say, within a new paragraph of text or something.
First time asking a question here, sorry if confusing.
First add somewhere this link list could go.
I'd put it in a unordered list (<ul></ul>). But you could just as well put it in a paragraph or a div.
I assume you know about objects and the for / in loop.
If not, this should help you get it:
https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
Here is the code I made for you. I have commented it along the way.
Just ask if something is unclear :)
Albania
Andorra
<select id="ddl2" onchange="configureDropDownLists('ddl2')">
</select>
<ul id='linkList'></ul>
<script type="text/javascript">
function configureDropDownLists(ddlBeingChanged) {
var ddl = document.getElementById('ddlBeingChanged');
var ddl1ChosenValue=document.getElementById('ddl1').value;
var linkLists = {
albania: {
"history": ['http://albania.example.com/history', 'http://albania.example.com/historyTwo'],
"legal guides": ['http://albania.example.com/guide', 'http://albania.example.com/guideTwo'],
},
andorra: {
"country overview": ['http://andorra.example.com/country', 'http://andorra.example.com/overview'],
"demographics": ['http://andorra.example.com/demographics', 'http://andorra.example.com/demographicsTwo'],
"legal guides": ['http://andorra.example.com/guide', 'http://andorra.example.com/guideTwo'],
}
};
if (ddlBeingChanged == "ddl1") {
console.log(ddl1ChosenValue);
for (var ddl2 in linkLists[ddl1ChosenValue]){
console.log(ddl2);
// Here the ddl2 variable will contain the first level of the object 'linkLists'. I.E. the country names.
createOption(document.getElementById('ddl2'), ddl2, ddl2);
}
} else if (ddlBeingChanged == "ddl2") {
var ddl2ChosenValue=document.getElementById('ddl2').value;
var linkArray=linkLists[ddl1ChosenValue][ddl2ChosenValue];
// The linkArray:
// Let's say someone chose andorra and demographics
// then linkLists[ddl1ChosenValue][ddl2ChosenValue] would be equivalent to linkLists.andorra.demographics
var linkListHTML="";
for (var i in linkArray){
var URL=linkArray[i];
linkListHTML+="<li><a href='"+URL+"'>"+URL+"</a></li>";
}
document.getElementById('linkList').innerHTML=linkListHTML;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
Edit: Fixed code bugs

javascript code doesn't work in IE8

i have two drop-down menus. On the selection of one menu the value of other changes. But in IE it doesn't work and my drop-down appears empty. here is my code
<div style="position:absolute; bottom:95px; right:631px;">
<select id='Country' name='Country' style="width: 148px;background-color:white;">
<option selected='selected'>All Countries</option>
<option>Australia</option>
<option>Cambodia</option>
<option>China</option>
<option>India</option>
<option>Indonesia</option>
<option>Hong Kong</option>
</select>
<select id='Airport' name='Airport' style="width: 148px;background-color:white;"></select>
</div>
JavaScript code
<script type="text/javascript">
(function(){
var bOptions = {"All Countries":["All Airports"], "Australia":["Sydney","Brisbane","Melbourne","Perth"], "Cambodia":["Phnom Penh"], "China":["Beijing","Guangzhou","Hangzhou","Kunmimg","Shanghai Pudong","Shanghai Hongqiao"],
"India":["Bangalore","Mumbai","Delhi"],"Indonesia":["Jakarta","Bali"],"Hong Kong":["Hong Kong"],"Japan":["Osaka","Narita","Haneda"],"Korea":["Seoul Gimpo","Seoul Incheon"],
"Macau":["Macau"],"Malaysia":["Kuala Lumpur"],"New Zealand":["Auckland"],"Philippines":["Manila"],"Singapore":["Singapore"],"Taiwan":["Taipei","Kaohsiung","Songshan"],"Thailand":["Bangkok","Phuket"],
"Vietnam":["Hanoi","Ho Chi Minh City"]};
var A = document.getElementById('Country');
var B = document.getElementById('Airport');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function(){
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for ( var i in bOptions[_val]){
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
</script>
anyone help?
Try to use op.innerText = bOptions[_val][i]; for old versions of IE because it doesn't supports op.text
Change your code like,
if(IE8)// use user_agent to get browser version and browser type
{
op.innerText = bOptions[_val][i];
}
else
{
op.text = bOptions[_val][i];
}
Read browser compalibilty and innerText
Here is a link which will sove your problem : http://jehiah.cz/a/firing-javascript-events-properly

Categories

Resources