Adding Placeholders to Contact Forms 7

HTML5 provides a placeholder attribute. How to get CF7 to use it? How to workaround stupid IE with jQuery?

Effect we want: show a placeholder in unmodified inputs, hide (delete) it when field gains focus, and restore it on blur if left empty. Preferably, don’t submit it.

Before HTML5 this trick was popular:

<input type="text" onfocus="if(this.value=='Message')this.value='';" onblur="if(this.value=='')this.value='Message';" name="foo">

Context

  1. In Contact Forms 7 (CF7), form fields are defined using shortcodes, not HTML, so can’t add the onfocus/onblur attributes. Unless we mess with CF7’s code, of course:
    $html = '<input type="text" name="'.$name.'" value="'.esc_attr($value).'" '.$atts.' onblur="if(this.value==\'\')this.value=\''.esc_attr($value).'\';" onfocus="if(this.value==\''.esc_attr($value).'\')this.value=\'\';">';

    And correspondingly for textarea, mutatis mutandis. But this is, obviously, unmaintainable.

  2. Unobtrusive JavaScript? Anyway, it would be more efficient (think many fields) to have jQuery do it instead.
  3. Using input’s default value as a placeholder doesn’t seem semantically correct.
  4. WAI?


2 Responses to Adding Placeholders to Contact Forms 7

  1. gilad :

    I found this and it works:
    I believe the same line I just posted could be added to line 70 of modules/text.php in the new 2.0 version, but I’m not sure about the block of code above it. So I’d suggest using:

    if ( $value != ” ) {
    $atts .= ‘ onfocus=”if (this.value == ” . esc_attr( $value ) . ”) {this.value = ”;}” onblur=”if (this.value == ”) {this.value = ” . esc_attr( $value ) . ”;}”‘;
    }

  2. Valentyn :

    in version 3.1.2 of this plugin, I found in line 105 this code:
    $html = ”;
    and just changed value=”‘ on placeholder. =)