bobbiloo
bobbiloo

Reputation: 432

Prefilled form fields

So I've inherited this form with prefilled form fields like "First Name", "Phone" or "Zip Code" so users will know what to do with the fields. But if anyone just hits the button, the form is passing "First Name", "Phone" or "Zip Code" into the database. The onFocus in the doesn't appear to be working. Any ideas?

<input type="" maxlength="25" name="firstname" tabindex="6" id="firstname" class="textfield" value="First Name" onFocus="if (this.value == 'First Name') {this.value = '';}">

Thanks in advance, -Bob

Upvotes: 0

Views: 1496

Answers (3)

RobG
RobG

Reputation: 147413

In addition to what Kolnik said, you can do a simple validation for text inputs that have a default value using something like:

if ( input.value == input.defaultValue || /^\s*$/.test(input.value) ) {
    // field value isn't valid
}

to check if the value is still the default, empty or whitespace. But remember that client–side validation is completely unreliable so do the real validation on the server.

Upvotes: 0

GregL
GregL

Reputation: 38121

As others have suggested, use the placeholder attribute to set the 'label' of the field. In addition, if you are already using jQuery to simplify your Javascript, you can use a plugin like this one which will add support for the placeholder attribute for non-HTML compliant browsers.

These plugins typically also take care of the crucial step of removing the placeholder text from your fields just prior to the form being submitted to the server, which should send blank values to the server, rather than the placeholder text.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324680

First off it's bad practice, labels should be labels, placed before the field they are labelling. Not inside.

Name: [________]
=== NOT ===
[Name____]

Just like a form on paper.

If you must have the text in the box, use the placeholder attribute. But be aware that only the newest browsers support it.

As for solving the problem of default values being submitted, just check if the value you're about to enter in the database is the default value and, if so, block it.

Upvotes: 1

Related Questions