Clearing default form values on submit

I’ve read a few solutions to this, but none seem to fit what I’d like to do. I’m quite new to JavaScript, so I’m trying to learn various solutions to problems and also what can and can’t be done.

What I’d like to know is can you, on submit, check all the form values on a page, or indeed within a specific form on a page, for their default values, and if any still have their default values as the text within that box, clear that value.

So using some generic form values as an example, if I had a form that had three text fields Name, Email, and Phone, all by default populated by their respective names, if someone changed the value of Name to “Adenv” but left the other two, on submit the script would change the values to:

Name - Adenv
Email - blank
Phone - blank

With blank indicating a blank field.

Is this possible?

On page load, you can store all the default values in variables.

When the submit button is clicked, compare the current value in each textbox with the value in its corresponding default value variable. If they are equal to each other then set the value of the textbox to ‘blank’.

This can all be done in javascript (in the user’s browser) or on the server if using a server side scripting language.

Thanks guys. Those are just the kind of ideas I was looking for. As I learn JavaScript a bit better, I can look into trying to implement them and experimenting with the outcome.

Each form field has a property called defaultValue which stores their initial value. You can compare the form field against that defaultValue property of the field, to check if they differ.

For example:


form.onsubmit = function () {
    var form, fields, field, i;
    form = this;
    fields = ['email', 'phone'];
    for (i = 0; i < fields.length; i += 1) {
        field = form.elements[fields[i]];
        if (field.value === field.defaultValue) {
            field.value = '';
        }
    }
}