When I wrote my very first HTML and PHP form, I was told that it's great to make the user's input visible even after sending the form by giving out the variables. So my first forms looked something like this:
<input type="text" name="name" value="<?php echo $name; ?>" />
I proceeded to check if there was any user input at all and to show an error if there wasn't:
if (!empty($name)) {
$flag_name = TRUE;
}
else {
echo "Please fill in your name";
$flag_name = FALSE;
}
I recently started working with JavaScript, and I stumbled upon a very helpful piece of code which makes it possible to write a default value into the form which gets cleared when you click on it. It looks like this and it works great!
<input id="name" name="name" onblur="if (this.value=='') this.value='Name'" onfocus="if (this.value=='Name') this.value='';" type="text" value="Name" />
To make it impossible for people to submit these default values, I changed my PHP check to check the default values:
if (!empty($name) && $name != 'Name') {
$flag_name = TRUE;
}
else {
echo "Please fill in your name";
$flag_name = FALSE;
}
I'm still not happy with my new form. If you try to submit it with the default values, you get an error message - great. But then you have to fill in everything again.
I'd like to combine this with my very first attempt, the one with the variables. The user is supposed to see a default value, which disappears when he clicks on the form. After filling in the gaps and clicking submit, they should still be able to see what they wrote.
Is this possible?
If you use the placeholder attribute you can omit the JS-fiddling on your input (1). Once you have separated the placeholder text from the actual value you can also forego the value check in PHP (2). After that it is a simple matter of outputting the submitted form value back into the form (3).
<?php
$name = '';
if (isset($_POST['name'])) // (2)
{
$name = $_POST['name'];
if (strlen(trim($_POST['name'])) > 0)
{
$flag_name=TRUE;
}
else
{
echo "Please fill in your name";
$flag_name=FALSE;
}
?>
<form method="post">
<!-- (1) (3)-->
<input id="name" name="name" placeholder="Your name here!" type="text" value="<? echo $name; ?>" />
</form>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments