WWW FAQs: How do I output the same form field value again?


2008-02-19: "Given that we've set a parameter on one web page and assigned it a variable name, how can I get the value of that variable and use it as a form field entry? I want to populate a form field automatically with a value passed from a previous page, but just using the variable name as the value of the field (value=var) doesn't do the job."

When you use PHP, this becomes a very simple problem.


<?php
function reprint($var) {
  # If $var exists in GET or POST, output it again.
  # Escape it properly so that we can't be hacked.
  if (isset($_REQUEST[$var])) {
    echo(htmlspecialchars($_REQUEST[$var]));
  }
}
?>
<!-- Now write the text field out again with the existing value
  as the initial value for this new page. Notice that we call
  the reprint function we just declared. -->
<input type="text" name="shoesize" value="<?php reprint('shoesize')?>"/>

You do need a PHP-enabled web hosting account to use this technique. But honestly, there's not much point in using forms if at the end of the day you can't do something meaningful with the fields, and that requires PHP, ASP.NET, Java or a similar language (not just JavaScript, which is purely client-side and can't save anything to a database or file where it does you, the webmaster, any good).

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!