Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 form placeholder fallback with form validation in Prototype

I've got an HTML5 form on my page with an email input that has place holder text in it. It works beautifully and I love the native validation!

I'm not sure how to serve old browsers best. I'm using a bit of javascript that copies the placeholder's text and imprints it as a value. It works well, but then the form validation goes off because there's text that isn't an email address in the form.

I do not want to lose the validation.. Any ideas?

HTML

<input id="email" type="email" placeholder="Enter your email address">

JavaScript (Prototype):

var Placeholder = Class.create({
    initialize: function (element) {
        this.element = element;
        this.placeholder = element.readAttribute('placeholder');
        this.blur();
        Event.observe(this.element, 'focus', this.focus.bindAsEventListener(this));
        Event.observe(this.element, 'blur', this.blur.bindAsEventListener(this));
    },
    focus: function () {
        if (this.element.hasClassName('placeholder'))
            this.element.clear().removeClassName('placeholder');
    },
    blur: function () {
        if (this.element.value === '')
            this.element.addClassName('placeholder').value = this.placeholder;
    }
});
Event.observe(window, 'load', function(e){
    new Placeholder($('email'));

});

EDIT:

Wouldn't it be great if browsers supporting placeholder ignored the value attribute?

EDIT 2:

No, I don't want to set the input type to text. That will change the validation's behavior from email syntax to spellcheck.

like image 429
technopeasant Avatar asked Jul 12 '11 07:07

technopeasant


1 Answers

User Modernizr to detect support for placeholder and only use your javascript to copy the placeholder text if support doesn't exist:

if(!Modernizr.input.placeholder){
  // copy placeholder text to input
}

This will prevent it from doing the copy on browsers supporting html5 form attributes like placeholder.

like image 58
kinakuta Avatar answered Sep 22 '22 19:09

kinakuta