Question

I'm trying to get what I think is a really nice bit of HTML5 in my website - the placeholder attribute for input fields.

But the way I've got it in my website degrades badly. Because I've skipped labels for the fields and used the placeholder as its label.

At the moment I have several input fields with placeholders, they look like this:

<input placeholder="hereismyplaceholder" />

But where HTML5 placeholder support is not available, I would like all of the input fields with placeholders to change to this. Obviously with their equivalent placeholder text:

<input onblur="if (this.value == '') {this.value = 'hereismyplaceholder';}" onfocus="if (this.value == 'hereismyplaceholder') {this.value = '';}" value="hereismyplaceholder" />

So I've pulled in Modernizr, and I'm getting it to detect the placeholders with the following javascript:

if (Modernizr.input.placeholder) {
} else {
// BUT I NEED SOMETHING IN HERE
}

But I have no idea what to do now. Because I have no experience with javascript, I'm not a developer.

The simplest solution would be the best please. I'm not fussed about good practice, I just want it to work for now.

Was it helpful?

Solution

You didn't ask for jQuery, but I didn't want to worry about cross-browser issues:

if (!Modernizr.input.placeholder) {
  $("input[type=text]")
  .focus(function(e){
      if (this.value == $(this).attr('placeholder')) {
         this.value = '';
      }         
  })
  .blur(function(e){
    setPlaceholder(this);
  }).each(function(index, el){
    setPlaceholder(el);
  });

  function setPlaceholder(el) {
    if (el.value  == '') {
        el.value = $(el).attr('placeholder');
    }
  }
}

OTHER TIPS

There is an example here, http://www.modernizr.com/docs/#input

For your specific use case, the code should be

// if placeholder isn't supported:
if (!Modernizr.input.placeholder){
  // use a input hint script
  setInputHint(document.getElementById('idoftheinputelement'),'hereismyplaceholder');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top