cotsweb.com Blog

Web design, Website development and life in the Cotswolds

Adding placeholders to IE8 & IE9 using jQuery

August 17th, 2014

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.