Local Storage With JavaScript - 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/

Related

How to set cookie to value of checkbox

I am trying to make a function that sets a cookie to a true/false value depending on if a checkbox has been clicked or not. I can then use this value when the page loads to render the checkbox as toggled.
HTML:
<form name="example">
<div class="checklist-item">
<label for="example">Example</label>
<input type="checkbox" id="example" name="example">
</div>
</form>
JS:
document.getElementById("example").addEventListener("click", exampleCookie)
function exampleCookie() {
document.cookie = "exampleCookie";
}
How might I use the function exampleCookie to be equal to the value of the checkbox?
sorry, i give you a referrence from here https://www.javatpoint.com/javascript-cookies
maybe it helps
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="color" onchange="display()">
<option value="Select Color">Select Color</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<script type="text/javascript">
function display()
{
var value = document.getElementById("color").value;
if (value != "Select Color")
{
document.bgColor = value;
document.cookie = "color=" + value;
}
}
window.onload = function ()
{
if (document.cookie.length != 0)
{
var array = document.cookie.split("=");
document.getElementById("color").value = array[1];
document.bgColor = array[1];
}
}
</script>
</body>
</html>

Session storage value not showing in second page

I am trying to get user input data in index.html. Then once user clicks on next, it should show the input data in the getapart.html page(second page). I am trying to use session storage for same. There are no errors, but it doesn't show the value. Not sure what I am doing wrong.
HTML
<html>
<head>
<script src = "showdata.js">
</script>
</head>
<body>
<fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
<form action="getapart.html">
<legend>Check for your part!</legend><br>
<label>Year:<br />
<select id="Year" onchange="show_yeardata()">
<option> - Select Year - </option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
</select>
<br>
<label>Make:<br />
<select id="Make" onchange= show_makedata()">
<option> - Select Make - </option>
<option value="Chevrolet">Chevrolet</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
<option value="Audi">Audi</option>
<option value="Toyota">Toyota</option>
</select>
<br>
<br><br>
<input type="text" id="showyear"><br>
<input type="text" id="showmake"> <br>
<input type="Submit"; value="Next" />
</form>
</fieldset>
</body>
</html>
getapart.html (second page to retrieve the user input and display the data)
<html>
<head>
<script src = "showdata.js">
</script>
</head>
<body>
Home
<br><br><br>
<div onload= "show_yeardata()" >
Year: <span id="ss_showyear"> </span><br>
Make: <span id="ss_showmake"> </span><br>
</div>
</body>
</html>
JS script (showdata.js)
function show_yeardata()
{
var year = document.getElementById("Year");
var year1 = year.options[year.selectedIndex].text;
document.getElementById("showyear").value=year1;
sessionStorage.setItem("key_showyear",year1);
document.getElementById("ss_showyear").innerHTML = sessionStorage.getItem("key_showyear");
}
function show_makedata()
{
var make = document.getElementById("Make");
var make1 = make.options[make.selectedIndex].text;
document.getElementById("showmake").value=make1;
sessionStorage.setItem("key_showmake",make1);
document.getElementById("ss_showmake").innerHTML = sessionStorage.getItem("key_showmake");
}
Looks like you are using same function for setting and getting the data. This increases complexity in many cases and brokes the system in your case.
Edit: Placement of the onload event is also invalid. You should put that to the body tag. See: How to add onload event to a div element
In the first page you successfully get data from selection and set to the session storage. However, when you trigger the same function again in the second page, year1 becomes undefined since there is no element with id "Year".
Then with these line you first put undefined to session storage then get it back immediately.
sessionStorage.setItem("key_showyear",year1);
document.getElementById("ss_showyear").innerHTML = sessionStorage.getItem("key_showyear");
Solution is simple. You split setter and getter functions like this.
function set_year_data() {
var year = document.getElementById("Year");
var year1 = year.options[year.selectedIndex].text;
document.getElementById("showyear").value=year1;
sessionStorage.setItem("key_showyear",year1);
}
function get_year_data() {
document.getElementById("ss_showyear").innerHTML = sessionStorage.getItem("key_showyear");
}
And in the first html:
...
<select id="Year" onchange="set_year_data()">
...
And in the secondhtml:
...
<body onload="get_year_data()" >
...

Javascript create input field using a select element

I am trying to create a simple website that calculates a card game score. The website will prompt a user to enter the number of players and return that number of fields for name inputs.
However, as my code stands currently, when a user enters the number of players, the website only shows one field for maybe a second and disappears. I was hoping that someone could help me (a novice programmer) on how to create input text fields dynamically with Javascript. Thanks!
//*****script.js*****
let response = parseInt(document.getElementById("players").value);
const playerNames = () => {
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>
You need not wrap your fields in a <form>. If you do this, since your button is type of submit: by default your browser will attempt to submit the form to another page & redirect. You can simply use <div> as a wrapper. Once you do this, you can remove the HTML attributes action & method since these attributes are no longer essential to your code base as you are no longer submitting a form.
As for the script, simply move the gathering of the input inside of the function not outside. So onclick event, that is the time you get the input from the <select>
<body>
<div class="start">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button onclick="playerNames()">Submit</button>
</div>
<script>
//*****script.js*****
const playerNames = () => {
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
</script>
</body>
When you submit the action takes hold and index.html is loaded. Use event.preventDefault() to stop this load. place response inside the function so each time submit is pressed it captures the value of the select box
//*****script.js*****
const playerNames = () => {
event.preventDefault();
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>

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" />

Get text from select tag in html

I have two dropdown menus named date and time respectively. I want to get the
text from the option tag when I click a button, but the javascript function does not seem to work. I 've found similar questions (and answers) about this but nothing worked. The code is below:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var index = document.getElementById("date").selectedIndex;
var date = document.getElementById("date").options[index].text;
window.alert("You selected: " + date);
}
</script>
</head>
<body>
<select name="date">
<option value="1">date 1</option>
.....
</select>
<select name="time">
<option value="1">time 1</option>
.....
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
You're selecting the element by id but you didn't assign the id anywhere.
You need to add the correct id to the item:
<select id="date" name="date">
....
<select id="time" name="time">
Or you could select the items by name:
var index = document.getElementsByName("date")[0].selectedIndex;
Note: getElementsByName returns an array, thats why the [0] was added to select the first item that has that name.
Change code to
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function collectData() {
var e = document.getElementById("date");
var strUser = e.options[e.selectedIndex].value;
window.alert("You selected: " + strUser);
}
</script>
</head>
<body>
<select name="date" id="date">
<option value="1">date 1</option>
..
</select>
<select name="time">
..
</select>
<button type="button" onclick="collectData()">Get data</button>
</body>
</html>
Try this:
function collectData() {
var ddl = document.getElementById("dateSelect");
var text = ddl.options[ddl.selectedIndex].text;
window.alert("You selected: " + text);
}
<select id="dateSelect" name="date">
<option value="1">date 1</option>
<option value="2">date 2</option>
<option value="3">date 3</option>
</select>
<button type="button" onclick="collectData()">Get data</button>
Here a CodePen
you are using getElementById('date').so add id attribute to select element.

Categories

Resources