I have this JavaScript code that processes and displays the value onto the same page; the value is entered using a textbox. I want to pass this value onto another page. this my code:
index.html:
<form action="display.html" method="post" id="name-form">
<p>
<label>Your full Name</label>:<br />
<input type="text" name="fullName">
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
<!-- <p id="result"></p>-->
<script>
var form = document.getElementById('name-form');
form.onsubmit = function (e) {
e.preventDefault();
var result = document.getElementById('result');
result.innerHTML = 'Hi ' + form.fullName.value;
console.log(form.fullName.value);
this.reset();
};
</script>
display.html
<p id="result"></p>
<script>
var form = document.getElementById('name-form');
form.onsubmit = function (e) {
e.preventDefault();
var result = document.getElementById('result');
result.innerHTML = 'Hi ' + form.fullName.value;
console.log(form.fullName.value);
this.reset();
};
</script>
my question is how do I get the value that is entered into the textbox to display onto another page?
If you have a static website, you should consider storing that value in localStorage. So that value will be available all across your web pages.
And if you have a dynamic website you can store that value in db and then request db for that value when you're on some other page.
Choose anyone of the approaches that fits in your case and application.
Read here about localStorage
Use cookies.
Save the name: document.cookie = "name=" + name
Load the name: name = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");
See here for a simpler way to load cookies
Related
I have two different pages. In the first one I have a form with name and email, and the second page should be the result page, and I want to show dynamically the name and email of the user from the form of the first page in the second page, and I precise, I want all this in pure javascript, not php. I tried the localStorage method, and this is what I got so far:
First page: Form page
HTML:
<label>Name:</label>
<input type="text" id="name" />
<label>Email</label>
<input type="text" id="email" />
<button onclick="testVariable()">Submit</button> <br />
Javascript
function testVariable() {
var strText = document.getElementById("name").value;
var strText1 = document.getElementById("email").value;
var result = strText + ' ' + strText1;
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("programX").textContent = result;
}
}
Second page:Result page
HTML:
<p>Hi
<span id="result"></span> thank you for subscribing to our service
</p>
Javascript:
// Check browser support
if (typeof(Storage) !== "undefined") {
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("programX");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
localStorage does not have any textContent property.
To set a localStorage
localStorage.setItem('key', 'value');
To get a localStorage value
localStorage.getItem('key');
So, what you are doing to set localStorage is wrong.
Replace
localStorage.setItem("programX").textContent = result;
with
localStorage.setItem("programX", result);
I have a form where it has a default value name "Alex". My goal is to save any changes made to the form through session Storage. It seems like my storage is getting saved on the browser, but my values are not updating in the form. On page refresh it keeps going back to the default value "Alex". I am not sure why that is happening if my values are being stored on the browser. Is my event handler the right approach for this?
JS Fiddle : https://jsfiddle.net/2yL7k8w5/20/
document.addEventListener("change", (evt) => {
const save_name = document.getElementById("name").value;
sessionStorage.getItem("name");
sessionStorage.setItem("name", save_name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
crossorigin="anonymous"></script>
<div class="well">
<form action="/person.php" method="post">
<label for="firstName">First Name</label>
<input id = "name"class="form-control" type="text" name="firstname" value="Alex">
</form>
</div>
I think the approach is okay but the problem is you've set value of input box in your HTML but you are not really updating the value with the value stored in sessionStorage.
So, use the following code to see the change:
let sname = sessionStorage.getItem("name");
let name = document.getElementById("name");
if(sname) {
name.value = sname;
}
document.addEventListener("change", (evt) => {
const save_name = name.value;
console.log(sessionStorage.getItem("name"));
sessionStorage.setItem("name", save_name);
});
You are saving in sessionStorage but you are not updating value on page load if session storage has any value in it.
Add below code.
$(document).ready(function() {
const name = sessionStorage.getItem("name");
if(name){
document.getElementById("name").value = name
}
})
I'm fairly new to the whole Javascript scene. Followed along with those online javascript tutorial things like code academy offers so I'm going by what I learned off of there and what I have read through other tutorials. Read though a few other posts to try and help me but I can't figure it out
So here's my question,
I am trying to take a form input, send it to a javascript file, then the javascript file returns a string which then I wish to reload the frame with. I'm attempting to make a simple chrome extension for me and my friends.
When I click "View Grade!" I get an error:
No webpage was found for the web address: chrome-extension://gcgddggimojbfgpbdmpfkmiofmpinjgb/location.href=getURL(account)?
and I can't determine if my javascript isn't working right or I just don't know how to send to a URL outside the "chromium" (as I call it) world.
This is my html file:
<form action="location.href=getURL('account')">
PSU Account (i.e. xyz123): <input type:"text" id="account">
<input type="submit" value="View Grade!">
</form>
And this is my javascript file:
function getURL(account) {
var psuAccount = document.getElementById(psuAccount);
// I changed strA to the ***.***.*** for this post
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB);
return(newURL);
}
I think this is exactly what <form>s are for...no need for Javascript for something like this. Try:
<form action="https://***.***.***/section/Gradebook/Student/default.aspx" method="GET">
PSU Account (i.e. xyz123): <input type="text" name="userId" />
<input type="hidden" name="reportMode" value="true" />
<input type="submit" value="View Grade!" />
</form>
The submit mechanism will automatically use the action attribute of the form. Since the method is "GET", it will also add a querystring of key/value pairs for elements in the <form> with a name attribute. So with your form, it will add a key "userId" with the value as the textbox's current value at time of submission. It will also add a key "reportMode" with the value "true". So the final URL that will be submitted is:
https://***.***.***/section/Gradebook/Student/default.aspx?userMode=true&userId=SOME_INPUT_STRING
If you need to use Javascript, try:
<div>
PSU Account (i.e. xyz123): <input type:"text" id="account" />
<input type="button" value="View Grade!" onclick="getURL();" />
</div>
with:
function getURL() {
var psuAccount = document.getElementById("account").value;
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB;
window.location.href = newURL;
}
want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.
I have text box called "userInput" and one submit button.I want to print the value of the text box which is entered by user like a stack(previous values also,not just the current value).
any idea..??
<input type="text" name="userInput"/>
<input type="button" name="sub" value="submit">
Thank in advance!
var stack = [];
$("input [name=userInput]").change(function () { stack.push(this.value); });
You can change that event to blur, focus, etc. depending on when you want the values recorded.
A submit button usually is for submitting a form. Submitting a form is sending a request to the server and refreshing the page. So in your server side script you could read the posted values and show them in the resulting page (you don't need javascript for this).
If you don't want to redirect you could handle the submit event and cancel the default submission:
var values = [];
$(function() {
$('#id_of_form').submit(function() {
// get the entered value:
var userInput = $(':input[name=userInput]').val();
// add the current value to the list
values.push(userInput);
// show the values
alert(values.join(", "));
// cancel the default submission
return false;
});
});
Tested solution:
<html>
<head>
<script type="text/javascript">
function AddToStack() {
var userInput = document.getElementById('userInput');
var stack = document.getElementById('stack');
stack.innerHTML += '<p>' + userInput.value + '</p>';
//clear input an refocus:
userInput.value = '';
userInput.focus();
}
</script>
</head>
<body>
<div id="stack"></div>
<input type="text" name="userInput" id="userInput"/>
<button type="button" name="sub" onclick="AddToStack();">Submit</button>
</body>
</html>