Im trying to use javascript in a HMTL contact form that shows text in the fields until the mouse has clicked on开发者_如何学Pythone of them. However my PHP seems to still think that there is text in the fields when its only javascript and not physical HTML. Can someone help me fix this issue?
Javascript / HTML Form
<form method="post" action="sendEmail.php">
<input type="text" name="name" id="name" onfocus="if (this.value == 'Your Name')
this.value = '';" onblur="if (this.value == '') this.value = 'Your Name';" maxlength="30"
value="Your Name" />
<input type="text" name="email" id="email" onfocus="if (this.value == 'Your Email')
this.value = '';" onblur="if (this.value == '') this.value = 'Your Email';" maxlength="30"
value="Your Email" />
<br /><br />
<textarea name="message" id="comments" value="Enter Your Message Here..." cols="60" rows="5"
onfocus="if (this.value == 'Enter Your Message Here...') this.value = '';"
onblur="if (this.value == '') this.value = 'Enter Your Message Here...';" >Enter Your Message Here...</textarea>
</form>
PHP
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 5) {
$error['comments'] = "Messages must be longer then 5 characters";
}
However my PHP seems to still think that there is text in the fields when its only javascript and not physical HTML
JavaScript still affects "physical HTML". If you're setting a value with JavaScript, PHP will see it when submitted. You may want to take a look at HTML5's placeholder
attribute (and a JavaScript library that simulates its functionality on older browsers).
You have value in the HTML, so even without JavaScript, those values will be send. Disallow submitting of the forms when the values are the default ones. For this run script on document ready, which records the value for each input as it's original value, and attaches the focus and blur handlers. Attach submit handler to the form, which checks the values being submitted if there are empty or the original ones.
The JavaScript you have adds or removes data, but it changes the value of your <input>
. The value
is what is sent over the wire by the browser when the form is submitted. You can either:
- Add a submit handler to your form to clear out any fields with their default values in them
- Use CSS + JavaScript to move your labels over your inputs and hide / show them as the user focuses / blurs the field (skip the new placeholder attribute entirely and imitate it using only JavaScript.)
- Remove your JavaScript completely and use the new
placeholder
attribute (and use a JavaScript shim to add support to older browsers that don't support the attribute) as @ceejayoz suggests.
<-- This is the best option
精彩评论