简体   繁体   中英

Displaying input value without a submit button to another page using javascript

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?

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);
  }); 
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM