问题
I am trying to display the result of an input value to another page. But this input does not have a submit button.
Thus, I am using keyup
to store the input data.
I have 2 pages, index1.php
and index2.php
index1.php:
<form>
<input type="text" name="nameValidation" id="nameValidation" placeholder="Name">
</form>
<div id="display"></div>
<script>
$(function() {
$('#nameValidation').keyup(function() {
var nameValisession = $('#display').text($(this).val());
sessionStorage.setItem("nameValiSession", nameValisession);
});
});
</script>
So, what I am doing here is that I am using the keyup
function to get the latest result and storing it as a variable. And then, I am assigning that variable into a sessionStorage
.
index2.php:
<div id="display"></div>
<script>
var nameValisession = sessionStorage.getItem("nameValiSession");
document.getElementById("display").innerHTML = nameValisession;
</script>
Here, I am just trying to retrieve the value of the variable nameValisession
However, this is not working for me. How do I go about sending the input value from index1.php
to index2.php
?
In the tutorial website (example 1) , it works perfectly for me when I tried their code.
Javascript in Page 1:
var favoritemovie = "Shrek";
sessionStorage.setItem("favoriteMovie", favoritemovie);
Javascript in Page 2:
var favoritemovie = sessionStorage.getItem("favoriteMovie");
console.log(favoritemovie);
So, can someone point me in the right direction on how to go about fixing the problem?
回答1:
The problem is because nameValisession
will hold a jQuery object, as that's what's returned from text()
, not the actual text value itself, and you cannot place objects in to localStorage. To fix this separate the variable declaration and text update steps.
I'd also suggest using the input
event instead of keyup
, as it also captures content added via the mouse:
$(function() {
$('#nameValidation').on('input', function() {
var nameValisession = $(this).val();
$('#display').text(nameValisession);
sessionStorage.setItem("nameValiSession", nameValisession);
});
});
来源:https://stackoverflow.com/questions/57623606/displaying-input-value-without-a-submit-button-to-another-page-using-javascript