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
}
})
Related
I am trying to re-populate the saved form inputs after a submit/page reload. The problem I'm running into is the input field populates the saved value (or just any string) but then resets almost immediately. What am I missing? Thanks
Flask (Server):
#app.route("/code", methods=["GET", "POST"])
def code():
value = request.form["field1"]
return render_template(
"code.html",
saved_inputs = value
)
Html:
<form action="{{ url_for('code') }}" method="post" id="form">
<label for="field1">Test Input 1 </label>
<input type"text" name="field1" id="field1">
<button type="submit" class="btn btn-primary" id="btnSubmit">Submit</button>
</form>
JS:
<script>
$("#form").on('submit', function(event){
event.preventDefault();
// convert form to JSON
var formData = new FormData(document.getElementById('form'));
var formJSON = {};
for (var entry of formData.entries())
{
formJSON[entry[0]] = entry[1];
}
result = JSON.stringify(formJSON)
console.log("results is: "+result);
// set JSON to local Storage
sessionStorage.setItem('formObject', result);
// submit form
document.getElementById("form").submit();
// decode sessionstorage object
var decodedObj = JSON.parse(sessionStorage.getItem('formObject'));
console.log("sessionStorage object: "+decodedObj);
// alert("value is: "+decodedObj["field1"]);
// alert("jinja value is: "+"{{ saved_inputs }}");
// retrieve localStorage and populate input
// this is not working as expected
document.getElementById("field1").value = "WHY ISN'T THIS SAVING??";
// document.getElementById("field1").value = '{{ saved_inputs }}';
})
</script>
I think the issue you are facing is that you are not checking when the page loads--only when the form is submitted. To load the form on page load we can use sessionStorage to check if the record exists and then load the object to the form.
$(function() {
const formObj = sessionStorage.getItem('formObject');
// Load object
if (formObj != null) {
console.log("Previous form session exists")
let decodedObj = JSON.parse(formObj);
console.log("sessionStorage object: " + decodedObj);
console.log("value is: " + decodedObj["field1"]);
// retrieve sessionStorage and populate input
console.log("Loading previous session");
document.getElementById("field1").value = decodedObj["field1"];
}
});
Proof of concept fiddle
You can try storing the values in local storage & then retrieve them whenever the page is reloaded. You have used Session Storage. See.
What is the wrong with this code? I got the exactly mobile number on the console but not on query routing on /search_user?mob ?
<input type="tel" name="message" id="mobile_input" value="">
<!--getting mobile no. from the input tag -->
<script type="text/javascript" defer>
e => {
e.preventDefault();
var mobInput = document.querySelector('#mobile_input');//get the input tag.
var moby = mobInput.value;//get mobile no.
console.log(moby);//be sure from the variable mob
mobInput.value='';//reset the input tag.
return moby;
}
</script>
<!-- query routing on /search_user?mob -->
Search
I tried something like this and this seems to work.
<form>
<input type="tel" name="message" id="mobile_input">
<button type="submit" onclick="handleSearch(document.getElementById('mobile_input').value)">Search</button>
</form>
<!--getting mobile no. from the input tag -->
<script type="text/javascript" defer>
// const handleChange = (value) => {
// var mobInput = value
// console.log(mobInput)
//
// }
const handleSearch = (input) => {
var searchValue = input;
console.log("This is the search value " + searchValue)
var url = '/search_user?mob=' + searchValue;
console.log(url)
window.location.href = url;
}
</script>
Explanation: I changed the a href element for a button element. Every time the button is clicked (onclick) the function handleSearch is called. This function takes as input the value of the input element with ID "mobile_input". Of course, you can clean up the function a bit more. After merging the url basis ('/search_user?mob=') with the input value (searchValue), the handleSearch function should redirect to the url (calling window.location.href). This last one you can of course change for the correct call to the server. Hope this helps.
Side note: you will see that there is a commented-out handleChange function. You could call this function in the input element to keep track of your changes in the console. this function is called using onChange, just like you use onClick with the search button.
For more info:https://www.w3schools.com/jsref/event_onchange.asp
I have an input field and I want to assign it a value dynamically fetched from DB. I will use that value later in a script. Here is my code below
<div data-ng-model="DashboardCounterItems">
<div data-ng-repeat="cItem in DashboardCounterItems">
<input type ="hidden" id ="myInput" value = {{cItem.dbMeetings.length}} />
</div>
</div>
Here {{cItem.dbMeetings.length}} is fetched from DB and assigned to myInput. Further when I check the value of this input in alert in script below, I get {{cItem.dbMeetings.length}} message instead of the value within it.
<script>
var iLenthv = document.getElementById("myInput").value;
alert(iLenthv);
</script>
Any help how can I do it. Or any other better way. I will really appreciate it.
I think your JS code will execute before DB data retrieval, can you check JS code within the setTimeout() Method?
<script>
setTimeout(function() {
var iLenthv = document.getElementById("myInput").getAttribute("value");
alert(iLenthv);
}, 3000);
</script>
Use .getAttribute() to get the value from a html attribute
function myFunction() {
var iLenthv = document.getElementById("myInput").getAttribute("value");
alert(iLenthv);
}
Hope it's helpfull
So we have to track the client side actual value, after the document is loaded. Would you adapt this piece of code and take a look at the console ?
<div data-ng-model="DashboardCounterItems">
<div data-ng-repeat="cItem in DashboardCounterItems">
<input type="hidden" id="myInput" value={{cItem.dbMeetings.length}} />
</div>
</div>
<script>
const test = () => {
var iLenthv = document.getElementById("myInput").value;
console.log("value:",iLenthv);
};
window.onload = test;
</script>
How can I get the value of an input field and print it on another HTML page? Here is my first page:
index.html
<form action="page.html" method="get">
<label>Enter your name:</label><br>
<input type="text" id="firstName" name="firstName"><br>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function myFunction() {
var name = document.getElementById('firstName').value;
</script>
I want to print that "name" variable on the "page.html". Please help.
I would suggest you to use localStorage , set this value :
localStorage.setItem('nameOfVariable', value);
and after loading other page you can get the value with
localStorage.getItem('nameOfVariable')
In your case :
function setName() {
var name = document.getElementById('firstName').value;
localStorage.setItem('name', name);
}
in page.html :
function getName() {
var name = localStorage.getItem('name');
// Do something
}
Try to use localStorage.
var name = document.getElementById('firstName').value;
window.localStorage.setItem('name', name);
And then in page.html page,
Try to get name
const name = window.localStorage.getItem('name')
And then print it.
You need to use the localStorage in the variable name like
document.getElementById("firstName").value = localStorage.name
You can acces the localStorage data from an another page like
document.getElementById("name").innerHTML = localStorage.name;
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