Implementing sessionStorage in between page hops - javascript

I have two codes, one is form.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
sessionStorage.n1 = $("#no1").val();
sessionStorage.n2 = $("#no2").val();
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>
and the other is main.html:
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = new Array();
var n2_arr = new Array();
$(function(){
n1_arr.push(sessionStorage.getItem("n1"));
n2_arr.push(sessionStorage.getItem("n2"));
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
I want these to work like this:
First, main.html will open, and on clicking on the 'Add' button, the form.html will open in the same browser tab. The user will enter two numbers in the text boxes with id's no1 and no2. The user will then click on 'Submit' and then again, main.html should open(again in the same browser tab). The user will continue to do this for as long as he wants. On clicking the 'Show' button, alerts of all the values entered by the user, separately in pairs, will occur. How can I achieve this? In this case, only the last entered pair is alerted.

first you have to run the command on console:
sessionStorage.clear();
main.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Main</title>
<script type="text/javascript">
var n1_arr = JSON.parse(sessionStorage.getItem("n1")) || [];
var n2_arr = JSON.parse(sessionStorage.getItem("n2")) || [];
$(function(){
$("#a").click(function(){
location.href = "form.html";
});
$("#s").click(function(){
for(var i = 0; i < n1_arr.length; i++)
{
alert(n1_arr[i] + " and " + n2_arr[i]);
}
});
});
</script>
</head>
<body>
<input type="button" value="Add" id="a">
<input type="button" value="Show" id="s">
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<script src="D:\frameworks\jquery-1.11.3.js"></script>
<meta charset="ISO-8859-1">
<title>Form</title>
<script type="text/javascript">
$(function(){
$("#sub").on("click", function(){
var n1 = sessionStorage.n1 || [];
if(n1.length > 0){
n1 = JSON.parse(sessionStorage.n1);
}
n1.push($("#no1").val());
sessionStorage.n1 = JSON.stringify(n1);
var n2 = sessionStorage.n2 || [];
if(n2.length > 0){
n2 = JSON.parse(sessionStorage.n2);
}
n2.push($("#no2").val());
sessionStorage.n2 = JSON.stringify(n2);
location.href = "main.html";
});
});
</script>
</head>
<body>
No1:<input type="text" id="no1">
No2:<input type="text" id="no2">
<br>
<input type="button" value="Submit" id="sub">
</body>
</html>

It would appear you are overwriting your existing n1 and n2 values.
sessionStorage stores key value pairs, with the value being a string. When you do sessionStorage.setItem('n1', 'test') it will overwrite the existing value.
What you need to do is read the existing value (it will be a string), parse it, append your new value on the end, then insert the whole object back into storage. When storing an object it will be best to stringify it as JSON first.
If you need to store complex objects like arrays etc you may find it better to use indexedDB.
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

Related

Add dynamically form fields dependencies in js

I am developing an app in Django. In my forms it is possible to have dependent fields. I would like to use this plugin. However, field dependencies may vary depending on the user's choices.
The fields in my forms look more or less like this:
<input type="text" name="name1" data-dependency="id_name2" class="textinput textInput form-control" id="id_name1">
The data-dependency attribute indicates which fields this field depends on. So in this case the name1 field will somehow depend on the name2 field.
I wrote this sample script to dynamically add dependencies:
$('document').ready(function(){
var name = document.getElementById("id_name1");
var data_dependency = name.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var elem = document.getElementById(d);
$(name).dependsOn({
'#id_name2' : {
values: ['yes']
}
});
}
});
At this point, I have a fixed id #id_name2 on which depends field name1 . Is there any way to pass on any element taken from the dependencies?
A simple working example (you only need to download two scripts):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
$(element).dependsOn({
'#myText1' : {
values: ['yes']
}
});
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>
</html>
The key to solving the problem was to know that dependsOn accepts the dictionary as an argument.
It is enough to create a suitable dictionary and pass it on as an argument.
So the solution is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="dependsOn.min.js"></script>
<script>
function get_id(element) {
return '#' + element.id;
};
$('document').ready(function(){
var element = document.getElementById("myText2");
var data_dependency = element.getAttribute('data-dependency');
var dependencies = data_dependency.split(";")
var i =0;
for(i=0; i<dependencies.length; i++){
var d = dependencies[i];
var tmp = document.getElementById(d);
var data = {}
data[get_id(tmp)] = {values: ['yes'] }
$(element).dependsOn(data);
}
});
</script>
</head>
<body>
<form id="myForm">
<label for="myText1">Type yes</label>
<input type="type" id="myText1">
<label for="myText2">Input</label>
<input type="text" id="myText2" value="" data-dependency="myText1">
</form>
</body>

inserting a variable into a jquery string to create a command

Stupid question no doubt but driving me mad!
Django template html but really a jquery question.
The following line checks a checkbox on my page....
$(id_exam_choices_1).prop('checked', true);
Fine no problem.
I want to create the same using a variable...
value = 1;
var thename = 'id_exam_choices_' + value;
alert(thename);
The alert shows the string is correct ....
How do I feed the variable into a command...??
$(thename).prop('checked', true);
I hope this is enough info - it seems straightforward but ....
Thanks.
Im not sure that I got your question correctly. If you are trying to check a checkbox depending on its number which is decided by value variable number then I would propose this solution. i.e if value=3 then checkbox with id= id_exam_choices_3 will be checked and so on.
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function () {
var value = 3;
var thename = "id_exam_choices_" + value;
$("body").find('#' + thename).prop("checked", true);
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="Scripts/jquery-3.3.1.min.js"></script>
</head>
<body>
<form method="post">
<span name="a">Check it</span> <input type="checkbox" id="id_exam_choices_1" />
<span name="a">Check it</span> <input type="checkbox" id="id_exam_choices_2" />
<span name="a">Check it</span> <input type="checkbox" id="id_exam_choices_3" />
</form>
</body>
</html>

How to dispaly values from a different html page using javascript?

I have the following code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
</body>
</html>
Another HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript">
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
</script>
</body>
</html>
I am trying to pass on the value 'name' and retrieve it on a different html page (results.html). How do I accomplish this? I am not sure what I am doing wrong. Please help. Thank you!
pass the variable in the url using GET like :
<form method="get" action="result.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
and retrieve it in the other page like :
<h2> Your Form Has Been Submitted </h2>
<script>
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
console.log(name) // this is your variable
document.querySelector('h2').innerText += name;
</script>
One way is: you could use the 'get' method on the form, and not 'post':
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>OrderUp</title>
</head>
<body>
<!-- Use method 'GET', not 'POST', to pass the form values via the url in the address bar -->
<form method="GET" action="results.html">
Name :
<input name="name" type="text">
<br>
<input value="Submit" type="submit">
</form>
</body>
</html>
Then, in result.html, use javascript to extract the name value from the page url.
result.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<span>Name Submitted: </span>
<span id="name-label"></span>
<script type="text/javascript">
// Get the value passed in the url by the form
var querystring = location.search;
// => ?name=Roger
// Remove the '?' at the beginning
var nameValuePair = querystring.replace(/^\?/, '');
// => name=Roger
// Split into parts
var parts = nameValuePair.split('=');
// The name is the second value
var name = parts[1];
// Set the name in the HTML element.
document.getElementById('name-label').innerHTML = name;
</script>
</body>
</html>
You cannot simply take a function from one html and put it into another. Using pure JavaScript and HTML the best way to accomplish this would be to make a JavaScript file, put the function there and load it on both pages. That way if you edit the function in one place, it will change in both.
The code would look like this:
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>OrderUp</title>
</head>
<body>
<form onsubmit="return results();" method="post" action="results.html" >
Name : <input name = "name" type= "text" id="name">
<br>
<input value = "Submit" type = "submit" >
</form>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
Page 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="OrderUp.css">
<title>Results</title>
</head>
<body>
<h2> Your Form Has Been Submitted </h2>
<script type="text/javascript" src="results.js"></script>
</body>
</html>
results.js
function results() {
var name = document.getElementbyId('name').value;
document.write(name);
}
Probably the simplest would be to append it to the url:
<script>
function goToResults() {
window.location = "results.html#" + document.getElementbyId('name').value;
}
document.getElementById("submit").onclick = goToResults;
</script>
<input id = "name" />
<button id = "submit" > Submit </ button>
And on results.html just get it from the location:
document.body.innerHTML += document.location.href.split("#")[1];
You need a way to save the information you want to share between pages. There are many options for javascript each with pros and cons
use the uri hash:
location.hash = myValue / var retrieveValue = location.hash;
use localstorage:
localStorage.setItem("key", "value"); / localStorage.getItem("key");
also document.cookie is an option, (you can look that one up as it's slightly more involved to implement with many good answes already around)

How to print an id get with document.getElementById?

HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="fuctions.js"></script>
<title>Count JS</title>
</head>
<body>
<fieldset>
<input type="number" value="1" id="num" min="1" max="5"/>
<button onclick="getValue()">
Submit
</button>
</fieldset>
</body>
</html>
JS:
function getValue() {
var x = parseInt(document.getElementById("num"));
alert(x);
}
I just want to print this value that I get using document.getElementById, but when I print appears it:
Can someone help?
.value returns value from input, in your case, you try convert DOMNode to Integer that will return NaN
var x = parseInt(document.getElementById("num").value);
Example
Add .value after document.getElementById
function getValue() {
var x = parseInt(document.getElementById("num").value);
alert(x);
}

Store textbox values in a div tag

I have a textbox having id=add, a div having id=get and a button named Add. Now I'm trying to enter values in textbox, save them in to an array and then save that array elements in the div tag (using javascript). But I'm unable to do so. Please help.
<html>
<head>
<title>Content</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="stylesheets/keyword.css" rel="stylesheet">
<SCRIPT language="javascript">
//
var data = new array();
data= document.getElementById('add').value;
function copy()
{
document.getElementById('get').innerHTML=data;
// document.getElementById('get').innerHTML= document.getElementById('add').value;
// return true;
}
</SCRIPT>
</head>
<body>
<input type="text" name="add" id="add"/>
<input type="button" name="but1" onclick="copy()" value="Add"/>
<div id="get" class="keyword"></div>
</body>
</html>
Update your code as,
<html>
<head>
<title>Content</title>
<script language="javascript">
function copy() {
var data = document.getElementById('add').value;
document.getElementById('get').innerHTML += data + "<br/>";
}
</script>
</head>
<body>
<input type="text" name="add" id="add" />
<input type="button" name="but1" onclick="copy()" value="Add" />
<div id="get" class="keyword">
</div>
</body>
</html>
PS:Array (not array) is not required here,
This is because data doesn't have any value, you are trying to read the value of the text box before setting a value and also it should be Array()
Try this instead
function copy()
{
var data = new Array();
data= document.getElementById('add').value;
document.getElementById('get').innerHTML=data;
}
JsBin
Three issues in your code:
array() is not recognized in javascript, it's Array().
You are trying to read the value of the text box before a value can be set to it here:
data= document.getElementById('add').value;
function copy(){
It should be:
function copy()
{
data[0]= document.getElementById('add').value;
data is an array. If you want to store a value, it should be used with an index.
JSFiddle
<html>
<head>
<title>Content</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="stylesheets/keyword.css" rel="stylesheet">
<SCRIPT language="javascript">
//
var data = new Array();
function copy()
{
data = document.getElementById('add').value;
document.getElementById('get').innerHTML = data; document.getElementById('get').innerHTML= document.getElementById('add').value;
// return true;
}
</SCRIPT>
</head>
<body>
<input type="text" id="add"/>
<input type="button" name="but1" onclick="copy()" value="Add"/>
<div id="get" class="keyword"></div>
</body>
</html>

Categories