Data to another page - javascript

I’m trying to have an input on one page where, let’s say, the user puts their name in, and then on clicking the submit button it takes them to another page where it says Hello “name”.
I seem to have it working, but then when I tried another page it doesn't carry the input over.
Is there a way to do this all on one page? I don’t want the output showing. If it's one page I want to make a transition so it's like a full screen input name: then submit transition into a new screen with Hello, “name”.
Code I have so far:
<label>Type your name: </label>
<input type="text" id="txtName">
<input type="button" value="click me" onclick="transfer()">
<script>
function sayHi(){
  var txtName = document.getElementById("txtName");
  var txtOutput = document.getElementById("txtOutput");
  var name = txtName.value;
  txtOutput.value = "Hi there, " + name + "!";
}
function transfer() {
location.href = "output.html";
}
</script>
New page
<input id="txtOutput">

Take a look in the localstorage API. Localstorage allows you to store data in the browser like this:
localStorage.setItem('item1', 'value1');
You can access later like this data later like this:
let cat = localStorage.getItem("item1");

You need to send value in page 1 to Page 2. In your case you are execute script in Page 1 and taking the user to Page 2 where the entire page loads again. Your executed script is gone.
Your Page1.html
<label>Type your name: </label>
<input type="text" id="txtName">
<input type="button" value="click me" onclick="transfer()">
<script>
function transfer() {
location.href = "output.html?name="+document.getElementById("txtName").value;
}
</script>
Now, your user will be taken to output.html?name={name he had entered}
output.html:
<input id="txtOutput">
<script>
// function to get data from URL.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
document.getElementById("txtOutput").value = "Hi "+findGetParameter("name");
</script>
Please let me know if it was helpful. However, I would suggest you to understand how back_end technologies work. and look at local storage.

Related

Display 'sum' on another page

I am currently having a problem displaying a calculated sum on the next page in javascript/html.
My calculation for defining the sum looks like this, where the 'sum + €' is displayed at the end.
function udregnPant() {
let sum = 0;
for (i = 0; i <= pantListParsed.length; i++) {
let totalPantKr = pantListParsed[i].aPantMoney + pantListParsed[i].bPantMoney + pantListParsed[i].cPantMoney;
sum += totalPantKr;
console.log(sum);
document.getElementById('sumAfPantB').innerHTML = sum + " €.";
}
}
In the following HTML input I want to display the sum as the value instead of '10 €'
<input type="text" name="amount" id="text1" value="10 €." readonly/>
Appreciate your help!
Make use of web storage.
sessionStorage - stores data for one session
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
localStorage - stores data with no expiration date
localStorage.getItem('label')
localStorage.setItem('label', 'value')
Example
function setSum(value) {
localStorage.setItem("sum", value);
}
function getSum() {
return localStorage.getItem("sum");
}
Live Example at JS Bin
References
Share data between html pages
HTML5 Web Storage
After calculating your value, redirect the user to a URL with the value in the query string (See Redirections in HTTP) -- this may look something like
window.location = http://mysite/page2.html?amount=12
On the new page, retrieve the value from the query string using the searchParams property (see URL.searchParams). Could look something like:
let params = (new URL(document.location)).searchParams;
document.getByElementId('text1').value = params.get('amount');
Here is a little example using local Storage, since so doesnt allow local storage try it in jsfiddle and
the code sample as well:
document.getElementById('btnSend').onclick = ()=>{
let total = document.getElementById('txtTotal').value;
if(!isNaN(total) && total > 0){
localStorage.setItem('total', total);
document.getElementById('txtTotal').value = '';
}
}
document.getElementById('btnLastTotal').onclick = ()=>{
var lastTotal = localStorage.getItem('total');
if(lastTotal !=undefined){
alert('last total is:'+lastTotal);
}else{
alert('No records found');
}
}
<input type="text" id="txtTotal">
<br>
<input type="button" id="btnSend" value="Save the total"> <input type="button" id="btnLastTotal" value="get Last Total">
Hope it helps

Append localstorage data to the body element on All session (Works also with reload)

I have some code from input, and I wanna to save it to some body element.
I can add it to the body, but it disappear when page is reloaded
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
var par = document.createElement('P');
par.innerText = storedValueBockName;
document.body.appendChild(par);
}
<form action="\" class="form-login" method="post" />
<input name="text" type="text" id="nameOfbook" required="" placeholder="Book name" />
<button onclick="store()" type="button">StoreText</button>
</form>
This question is basically asking how to retrieve a stored value from localStorage.
So you're setting the value in localStorage, but when you reload the page, you need to have a script that checks to see if there's a value in localStorage and add that data to your page if it is found there.
I would suggest something like:
<script>
var setText = function(text) {
var par = document.createElement('P');
par.innerText = text;
document.body.appendChild(par);
}
var checkLocalStorage = function() {
var value = localStorage.getItem("nameOfbook")
if (value) {
setText(value)
}
}
checkLocalStorage()
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
setText(storedValueBockName)
}
</script>
So I moved the code that appends the title to the page into its own function so that it can be used by both store() and checkLocalStorage(). checkLocalStorage looks to see if there's a value set for nameOfbook and, if there is, passes that value to setText.
Should do the trick.

how can I call tab key event in javascript

Here is my simple data
John Smith Individual 010987654
I have three textboxes and the above data will automatically insert in the first textbox of my web page.
My problem is
How can I make as soon as data is inserted in the textbox (means when textbox’s onchange event is fired)
First, javascript will find ‘tab’ space in this string
Second, if find ‘tab’ space in the string, javascript will press ‘tab’ key and insert data in the another text box.
Here's a plain old DOM-0 JavaScript solution, just for fun.
document.getElementById('the_form').onchange = function() {
var field = this[0];
var parts = field.value.split('\t');
for (var i = 0; field = this[i]; i++) {
field.value = parts[i] || '';
}
}
http://jsfiddle.net/vKaxP/
I thought you want to split those texts into different textboxes, so I got something like:
$("#a").change(function(){
var s = $(this).val();
if (s.match(/\t+/)) {
var a = s.split(/\t+/);
$('#a').val(a[0]);
$('#b').val(a[1]);
$('#c').val(a[2]);
}
});
if you type a b c into the first input box, press tab or enter, b and c would appear into other textboxes, repectively.
I use \s(space) for test in jsfiddle. You could just change it to \t for tab.
Here is prototype of what you need to do.
HTML:
<div>
<input id="a" />
</div>
<div>
<input id="b" />
</div>
JavaScript:
$('#a').on('change', function () {
var value = $(this).val();
// Test if string has a tab:
if (/\t/.test(value)) {
// Just set the value of the other text box
// And set focus:
// Using jQuery that would be:
$('#b').val(value).focus();
}
});
Working demo: http://jsfiddle.net/tkirda/XmArP/
If I correctly understand the question as "The server puts all the data into one field, tab separated, and I want to split it up into several textfields", then try this:
On load:
var fields = [$("#firstField"), $("#secondField"), $("#thirdField")];
var data = fields[0].val().split(/\t/);
for (var i = 0; i < 3; i++) {
fields[i].val(data[i]);
}

Input entry is not catched in Javascript

I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Categories

Resources