Adding placeholders to IE8 & IE9 using jQuery

The placeholder attribute on the input statement is a useful way of providing prompts to the user without cluttering up the screen, it is well supported by all modern browsers but sadly not by versions of Internet Explorer before IE10.  There is a good jQuery plugin called watermark which solves the problem but you need to apply it to the  required fields, they suggest something like.

$( '#inputId' ).watermark( 'Required information' );

That is fine but I don’t really want to separately to each field, particularly if I have already populated the placeholder for each field.  So being lazy I have written a little bit of jQuery which takes the existing placeholder for each field and adds it as a watermark.


<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.watermark.min.js"></script>

<script type="text/javascript">
   $(document).ready(function () {
       /*
        * Set watermarks on input fields; IE8 & IE9 don't support placeholders
        * This routine extracts the placeholder text from the HTML input statements and 
        *    passes it to the jQuery watermark plugin
        * so we don't have to separately maintain the watermark text
        */
         $('[placeholder]').each(function () {
           var placeholderText = $(this).attr('placeholder');
           $(this).watermark(placeholderText);
       });
   });
</script>

Obviously this requires that you have included jQuery and the jQuery watermark plugin earlier in your code as I have in the example but now every input field that I add a placeholder to
<input type="text" placeholder="Put some text in here" name="textField" />
will display that placeholder text whether the user is running the latest version of Chrome or an antique version of Internet Explorer.

I hope you find this useful.

Tags: , , ,

One Response to “Adding placeholders to IE8 & IE9 using jQuery”

  1. Tiji says:

    Nice article. Like watermark there are many other placeholder Polyfills in javascript too that one can use. The one by jamesallardice is also great.

Leave a Reply