Javascript select option application - javascript

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

Related

How do I change the select option value contents using js

I'm not good at javascript but I tried this...
I'm trying to make an option for a user to switch to another page after searching for an item.
The user for example will searches for a Mercedes under cars section then the options value can change to the Mercedes links page as well as can change to GMC links page is the user searches for gmc. This code seems not to work.
Below is the code:
<div class="all" id="note">
Some content will be posted here...
</div>
<select id="marketing" onChange="window.open(this.value)" multiple>
<option value="1">cars</option>
<option value="2">houses</option>
<option value="3">Promotion</option>
</select>
<script type="text/javascript">
var cars = ['mercedes']
$('#marketing').change(function(){
if($(this).val() == '1'){
if cars[0] ==='mercedes';{
$(this).val() == "http://www.cars.com/mercedes";
}
}
});
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var cars = ['mercedes']
function myFunction() {
var x = document.getElementById("marketing").value;
var companey = document.getElementById('companies').value;
console.log(x + companey);
if (x == 1 && companey == "mercedes") {
var url =
window.open("http://www.cars.com/mercedes" , '_blank');//for new tab
//for same tab
//window.open('http://www.cars.com/mercedes');
}
}
</script>
</head>
<body>
<!this is a working sample hope this will help>
<div class="all" id="note">
Some content will be posted here... <br />
<input type="text" id="companies">mercedes</input>
</div>
<select id="marketing" onchange="myFunction()">
<option value="0"></option>
<option value="1">cars</option>
<option value="2">houses</option>
<option value="3">Promotion</option>
</select>
</body>
</html>

Disable option when clicked in select

How do I make disable an option when a select is clicked? Here is my code, which does not work. There are no errors in the console.
Here it is:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var numSelect = document.getElementsByClassName("numSelector");
for (var i = 0; i < numSelect.length; i++) {
numSelect[i].innerHTML="<span class='firstSelector'><option>Select Number</option></span><option>1/2</option>";
numSelect[i].onclick = disableSelect;
}
}
function disableSelect() {
for (var a = 0; a < document.getElementsByClassName("firstSelector").length; a++) {
document.getElementsByClassName("firstSelector")[i].innerHTML="<optgroup>Select Number</optgroup>";
}
}
</script>
</head>
<body>
<select class="numSelector"></select>
<select class="numSelector"></select>
</body>
</html>
I'm not sure what you want but here is the ways to disabled dropdown value.
<select id="select1" onclick="disableSelectedItem(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<select id="select2" onclick="disableFirstItemOnly(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<script type="text/javascript">
function disableSelectedItem(ddl) {
var value = ddl.options[ddl.selectedIndex].value;
var count = ddl.length;
for (var i = 0; i < count; i++) {
if (ddl.options[i].value == value)
ddl.options[i].disabled = true;
else
ddl.options[i].disabled = false;
}
}
function disableFirstItemOnly(ddl) {
ddl.options[0].disabled = true;
}
</script>
Just use pure HTML
<select required>
<option value="" selected disabled>Select Number</option>
<option>1</option>
<option>etc..</option>
</select>
You could also add the hidden attribute if you don't want it to show up in the dropdown too (at the moment it is visible but disabled)
The required attribute on the <select> means that not choosing a number will prevent submission (though you should still validate serverside)

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/

Javascript dropdown list working, but displaying empty values

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>

Categories

Resources