Search code examples
javascriptjqueryvalidationform-processing

prepopulate form with jquery and validation


I am using the following code, to prepopulate entries for browsers that do not support html5 placeholder. I'm having 2 problems with it:

1) It only works for text boxes, not text areas... suggestions? 2) I'm using the jquery validation plugin, and since the following code adds a value, the plugin thinks that there is something entered, and won't validate that field... Is there any way around this?

I need a way to still have effective validation, but be able to prepopulate the fields

$('input:text').each(
    function(){
        $(this)
            .val($(this).attr('placeholder'))
            .css('color','#999');
        $(this).click(
            function(){
                $(this)
                    .val('')
                    .css('color','#000');
            });
        $(this).blur(
            function(){
                if ($(this).val() === ''){
                    $(this)
                        .val($(this).attr('placeholder'))
                        .css('color','#999');
                }
            });
    });
}

Thanks!


Solution

  • 1) Include textarea in your selector.

    Example

    $('input[text], textarea')
    

    2) On submit of the form, if the value in the input is equal to the defaultValue property, set its value to blank ('').

    Example

    form.validate({
       submitHandler: function(form) {
    
           form.find('input[text], textarea').each(function() {
               if (this.defaultValue == this.value) {
                   this.value = '';
               }
           });
    
           form.submit();
       }
    })