Javascript dropdown list working, but displaying empty values - javascript

I have 2 dropdrown lists written in javascript.Upon loading the page and clicking them, they dropdown and display what would normally be values, except the values are empty.
E.g
---------------
| Gender |
---------------
| |<-- Is supposed to show "M"
---------------
| |<--Is supposed to shown "F"
My code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function load(){
AgeDropDown();
genderlist();
}
function AgeDropDown(){
var list= document.getElementById("UserProfileAge");
for(var i=1;i<100;i++)
{
var opt = document.createElement("option");
opt.value= i;
list.appendChild(opt);
}
}
function genderlist(){
var list= document.getElementById("UserProfileGender");
var choices=["M","F"];
for(i=0;i<choices.length;i++)
{
var opt = document.createElement("option");
opt.value= choices[i];
list.appendChild(opt);
}
}
function load(){
AgeDropDown();
genderlist();
}
</script>
</head>
<body onload="load()">
<?php
include("usermenubar.inc");
?>
<form id='UserProfile' name='UserProfile' method='POST' action='editdetails.php'>
<div class='UserDetails'><!--dropdown-->
Age:<select id='UserProfileAge' name='UserProfileAge' onchange='AgeDropDown()'>
<option value=''>Please enter your age</option>
</select>
</div>
<div class='UserDetails'><!--Dropdown-->
Gender:<select id='UserProfileGender' name='UserProfileGender' onchange='genderlist()'>
<option value=''>Please enter your gender</option>
</select>
</div>
<input type='submit' name='UserProfileSubmit' value='Save Changes'/>
</form>
</body>
</html>

you can also use new Option to dynamically add options.. to an HTMLSelectElement using the add method...
function AgeDropDown(){
var list= document.getElementById("UserProfileAge");
for(var i=1;i<100;i++)
{
var opt =new Option(i,i) ;
list.add(opt);
}
}
function genderlist(){
var list= document.getElementById("UserProfileGender");
var choices=["M","F"];
for(i=0;i<choices.length;i++)
{
var opt = new Option(choices[i],choices[i]) ;
list.add(opt);
}
}
also i noticed a strange thing.. in your markup...
<select id='UserProfileAge' name='UserProfileAge' onchange='AgeDropDown()'>
and
<select id='UserProfileGender' name='UserProfileGender' onchange='genderlist()'>
you are calling your both functions everytime the value of the select changes.. so new options will be added in the select.. i don't know why you are doing that??

Options can have both value and text. You're only setting the value, so it will function properly, but not display any text.
The HTML you're generating would look like this:
<select>
<option value="M"></option>
<option value="F"></option>
</select>
You want this:
<select>
<option value="M">M</option>
<option value="F">F</option>
</select>
So, also set the textContent of the option elements, and innerText for IE support.

You can do it like this (check out jsfiddle to see it running):
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function load(){
AgeDropDown();
genderlist();
}
function AgeDropDown(){
var list= document.getElementById("UserProfileAge");
for(var i=1;i<100;i++)
{
var opt = document.createElement("option");
opt.value= i;
opt.text = i;
list.appendChild(opt);
}
}
function genderlist(){
var list= document.getElementById("UserProfileGender");
var choices=["M","F"];
var choicesText=["Male","Female"];
for(i=0;i<choices.length;i++)
{
var opt = document.createElement("option");
opt.value= choices[i];
opt.text = choicesText[i];
list.appendChild(opt);
}
}
function load(){
AgeDropDown();
genderlist();
}
</script>
</head>
<body onload="load()">
<?php
include("usermenubar.inc");
?>
<form id='UserProfile' name='UserProfile' method='POST' action='editdetails.php'>
<div class='UserDetails'><!--dropdown-->
Age:<select id='UserProfileAge' name='UserProfileAge' onchange='AgeDropDown()'>
<option value=''>Please enter your age</option>
</select>
</div>
<div class='UserDetails'><!--Dropdown-->
Gender:<select id='UserProfileGender' name='UserProfileGender' onchange='genderlist()'>
<option value=''>Please enter your gender</option>
</select>
</div>
<input type='submit' name='UserProfileSubmit' value='Save Changes'/>
</form>
</body>
</html>

Related

When I click multiple listbox dynamic textbox must be generated Javascript

Here I have multiple listbox and when I click an option dynamic textbox should be generated Javascript.
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" multiple onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
Solution using JS Core:
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var input = document.createElement('input');
input.value = selectBox.options[selectBox.selectedIndex].value;
input.type = text;
document.getElementbyId('input_fields').appendChild(input);
}
Add the following div to your body
<div id="input_fields"></div>
The Solution becomes much easier if you use jQuery:
function changeFunc() {
$("#input_fields").append("<input type='text' value='"+$("#selectBox").val()+"'>");
}
This will simply append the HTML inside the div with id="input_fields"
is this you want?
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
var textP = document.createElement('p');
textP.innerHTML = selectedValue;
document.body.appendChild(textP);
}
</script>
</head>
<body>
<select id="selectBox" multiple onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

Javascript select option application

I am trying to create the select application using Javascipt only. I got to know about this code on internet
<!DOCTYPE html>
<html>
<head>
<title>Select Options</title>
</head>
<body>
<h2>Choose your car</h2>
<hr>
Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Hyundai">Hyundai</option>
<option value="Honda">Honda</option>
<option value="Maruti">Maruti</option>
</select>
<hr>
Choose Car Model
<select id="slct2" ></select>
</body>
<script type="text/javascript">
function populate(s1,s2){
var s1,s2;
s1 = document.getElementById(s1);
s2 = document.getElementById(s2);
if(s1.value=='Hyundai'){
optionArray=['Please Select Car','i10','i20','Verna']
} else
if(s1.value=='Honda'){
optionArray=['Please Select Car','Amaze','Jazz','City']
} else
if(s1.value=='Maruti'){
optionArray=['Please Select Car','Swift','Dezire','Ciaze']
}
for (var i = 0; i < optionArray.length; i++) {
var store = optionArray[i];
var createNewEl = document.createElement('option');
createNewEl.innerHTML = store;
s2.appendChild(createNewEl);
}
}
</script>
</html>
This is the full code I use now to write this apllication but I everytime I select option from car make ** and when I select another option fromcar make**, it does not delete the previous options from car model and the list gets increased so on everytime I select option from car make
First, you need to import jQuery. Paste this between <head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your script is appending new values to end of the select list, so it have to remove all old values.
$("#slct2 option").remove();
I tested it and works fine for me. Here is full, working code.
<!DOCTYPE html>
<html>
<head>
<title>Select Options</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Choose your car</h2>
<hr>
Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Hyundai">Hyundai</option>
<option value="Honda">Honda</option>
<option value="Maruti">Maruti</option>
</select>
<hr>
Choose Car Model
<select id="slct2"></select>
</body>
<script type="text/javascript">
function populate(s1,s2){
var s1,s2;
s1 = document.getElementById(s1);
s2 = document.getElementById(s2);
$("#slct2 option").remove();
if(s1.value=='Hyundai'){
optionArray=['Please Select Car','i10','i20','Verna']
} else
if(s1.value=='Honda'){
optionArray=['Please Select Car','Amaze','Jazz','City']
} else
if(s1.value=='Maruti'){
optionArray=['Please Select Car','Swift','Dezire','Ciaze']
}
for (var i = 0; i < optionArray.length; i++) {
var store = optionArray[i];
var createNewEl = document.createElement('option');
createNewEl.innerHTML = store;
s2.appendChild(createNewEl);
}
}
</script>
</html>
EDIT:
If you don't want to use jQuery just replace this $("#slct2 option").remove(); with this:
while (s2.firstChild) {
s2.removeChild(s2.firstChild);
}
s2.appendChild(createNewEl); adds to a list of whatever
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_appendchild

how to add textbox value to dropdown list

I have one Dropdown list it has some values and other option,when i select other option it shows textbox ,i have to enter some text into it ,so i want to add that value to dropdown lilst,so how can i solve this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('color');
if(val=='pick a color'||val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>
Add a button, get select value to check if it's others or pick / display the button according to it.
To add a new element, create an option and add it inside the select with x.add(option);
function CheckColors(){
var element = document.getElementById("mySelect");
var element2 = document.getElementById("color");
var element3 = document.getElementById("addColor");
if(element.value =='pick a color'|| element.value =='others'){
element2.style.display='block';
element3.style.display='block';
}
else {
element2.style.display='none';
element3.style.display='none';
}
}
function addValue(){
var textToAdd = document.getElementById("color").value;
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = textToAdd;
x.add(option);
}
https://jsfiddle.net/7woyyw4h/
Please check below code hope it will helpful for you.
<script>
$(document).ready(function(){
$('#btnAddToBegining').click(function(){
var data = $("#txtAdd").val();
$("#ddlList").prepend("<option value='0' selected='selected'>"+ data +" </option>");
});
$('#btnAddToEnd').click(function(){
var data = $("#txtAdd").val();
$("<option value='6'>" + data +"</option>").appendTo("#ddlList");
});
});
</script>
<select id="ddlList">
<option value="1">ASP.NET</option>
<option value="2">C#</option>
<option value="3">VB.NET</option>
<option value="4">HTML</option>
<option value="5">jQuery</option>
</select>
<input type="text" id="txtAdd" />
<br/><br/>
<input type="button" id="btnAddToBegining" Value="Add Item to Begining" />
<input type="button" id="btnAddToEnd" Value="Add Item to End" />

How to get the index of a selected item in listbox and add to listbox two with button?

I am looking to get the index of the selected item in a list box to add the selected item to list box 2.
The listbox was created in HTML.
<div class="clearfix">
<div class="select-container">
<select name="sometext" size="5">
<?
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheets()[1]);
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:A"+lastRow);
var data = myRange.getValues();
?>
<? for (var i = 0; i < data.length; ++i) { ?>
<option><?!= data[i] ?></option>
<? } ?>
</select>
</div>
<div class="buttons">
<div><button onclick='addMonitoredFolder()' id='button1'>Add</button></div>
</div>
So when I press button 'Add', I want the currently selected item in list box 1 to be added to listbox 2. It would be good that if the user selects multiple options in the list then it will add these or at least know how to handle this. I have function addMonitoredFolder in there because I was trying to figure it out by just can't get my head around it.
<div class="select-container">
<select name="sometext" size="5">
<option>option</option>
</select>
</div>
Thanks!
Here is code that can get multiple selections from a list, and transfer the choices to the second list:
index.html
<!DOCTYPE html>
<html>
<body>
<div>List Box One</div>
<select id="slctOne" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<div>List Box Two</div>
<select id="slctTwo" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<button onmouseup="getAndTransfer()">Get Choices</button>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
</body>
</html>
JavaScript.html
<script>
window.getAndTransfer = function() {
var allChoices = getMultiple();
putChoicesIntoSelectTwo(allChoices);
};
window.getMultiple = function() {
//console.log('getMultiple ran')
var allOptionNodesSelected = document.getElementById('slctOne').querySelectorAll('option:checked');
var howManySelected = allOptionNodesSelected.length;
console.log('number of option nodes: ' + howManySelected);
var optionElmt1 = allOptionNodesSelected[0];
console.log('optionElmt1.selected: ' + optionElmt1.selected);
var i=0,
arryAllOptions = [];
for(i=0;i<howManySelected;i+=1) {
console.log('optionElmt1.selected: ' + allOptionNodesSelected[i].value);
arryAllOptions.push(allOptionNodesSelected[i].value);
};
return arryAllOptions;
};
window.putChoicesIntoSelectTwo = function(theChoices) {
//Get select list two element
var selectListTwo = document.getElementById('slctTwo');
var allOptions = selectListTwo.getElementsByTagName("option"); //Get all current options inside of this select tag
var i = 0, thisOptionVal="";
//console.log(allOptions.length);
for (i=0;i<allOptions.length;i+=1) {
thisOptionVal = allOptions[i].value;
if (theChoices.indexOf(thisOptionVal) !== -1) {
allOptions[i].selected = true;
} else {
allOptions[i].selected = false;
};
};
};
</script>

Local Storage With JavaScript

I want to store a string locally so when the user reloads the page it saves what was last there.
I looked at this and tried to implement it.
I had this code which basicllay has a button and a dropdown list of colors to change the background.
When I close and reopen the doc I want it to be the color that I saved.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<form>
<script language="JavaScript">
<!--
function inputForm(){
var color = document.getElementById("color");
var outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
//-->
</script>
</body>
</html>
I made this code to do that but it didn't work
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="storeColor()">
<form action="">
<label>
<select id="color">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#FFCC00">Orange</option>
<option value="#FFFF00">Yellow</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
<option value="#663366">Indigo</option>
<option value="#FF00FF">Violet</option>
</select>
</label>
<input type="button" onClick="inputForm()" value="change color"/>
<input type="button" onClick="storeColor()" value="save color"/>
<script>
var outputContents;
function inputForm(){
var color = document.getElementById("color");
outputContents=color.value;
document.body.style.backgroundColor = outputContents;
}
function storeColor(){
// Store
localStorage.color = outputContents;
// Retrieve
document.body.style.backgroundColor = outputContents;
}
</script>
<form>
</body>
</html>
Local storage in JavaScript is uses (key, value) pairs of strings so if you wanted to save the value This is my test value. you would need to give it a key that you can get it from later, for example myTestValue.
So in code this would be
// set the value in window.localStorage
window.localStorage.setItem('myTestValue', 'This is my test value.')
// get the value from window.localStorage
window.localStorage.getItem('myTestValue')
Here is some more information: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You code is almost complete. You only need to apply background color on window load. I added one more function applyColor:
function applyColor(color) {
color = color || localStorage.color;
document.body.style.backgroundColor = color;
// Select corresponding option in selectbox
var select = document.getElementById("color");
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == color) {
select.options[i].selected = true;
return;
}
}
}
applyColor();
Also note that when page is loaded we should also select the option from selectbox corresponding to currently saved color.
Demo: http://jsfiddle.net/sd2Cx/

Categories

Resources