简体   繁体   中英

How to retain value of text input while navigating to back page in PHP?

I want to retain entered value in text box after navigation. I am explaining my code here.

**main.php**

<html>
    <head></head>
    <body>
        <input type="text" id="myname" value="">
        <a href="next.php" id="second.php">Next</a>
   </body>
</html>

**next.php**

<a href="main.php">Back</a>

I don't want to use 'button' field here. On link navigation I want to retain the entered value in text box field. I am using php, html

您应该将其保存在Cookie /会话中。

Or you can use localStorage too. Here's a link to read more

  <form id="myform" name="myform" method="POST" action="next.php">
       <input type="text" name="query" id="query">
     <a href="javascript: submitform();">Submit</a>
        </form>
<script type="text/javascript"> 
 function submitform(){
   // alert('form submit');
document.forms["myform"].submit();
}      </script>

And in next.php $_SESSION['last_search_term'] = $_REQUEST['query']; echo $_SESSION['last_search_term']; $_SESSION['last_search_term'] = $_REQUEST['query']; echo $_SESSION['last_search_term'];

This will work . I have check it

I would use cookies. Note sessions and Opera back button do not work well together .

However if you want a cookieless solution you can use "window.name" string which is persistent ie its value is retained on navigation between pages. No need for a button as you required.

Just add this code before the closing </body> tag.

<script>
// on navigation to, or back: load users input from previous page (if any)
  document.getElementById("myname").value = window.name;  
// save value on navigation out
  window.onbeforeunload = function() {
    window.name = document.getElementById("myname").value;
    return;
  }
</script>

Assuming you give your text field the same id you can use the same js without modification on both/all pages.

The basic example code above should work with all modern browsers and most old browsers (even Opera since 2013). Modify it to use an event listener sanitize/check for empty values etc as required

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