zw

Swapping input field placeholder text with jQuery

Here is a quick and easy way to handle swapping placeholder text in an input field with jQuery. This is typically used when you have a text box where the design does not allow enough room for a label element to describe the purpose of the field. In this case, like a global search box, the input field is pre-populated with a descriptive text such as “Search”. When the user clicks the field, “Search” is removed, so the field is empty and ready for input. When the field loses focus, “Search” is replaced if the user hasn’t typed anything. This is best seen with an example. The following text box illustrates how it works. Try clicking in and out of the box.



And the jQuery code: (for jQuery 1.3 or later)

$(document).ready(function(){ 
  $('input[type=text]').focus(function(){ 
    if($(this).val() == $(this).attr('defaultValue'))
    {
      $(this).val('');
    }
  });
  
  $('input[type=text]').blur(function(){
    if($(this).val() == '')
    {
      $(this).val($(this).attr('defaultValue'));
    } 
  });
}); 

Works in IE6, IE7, FF2, FF3, and Safari.

IE6 links showing blank pages

I recently had a problem with a site I was building where clicking any link in IE6 would just show a blank page. After I hit refresh, it would show the page correctly. It worked in every other browser, and the markup was valid. After googling around, the only answers I could find suggested IE6 was corrupted. I knew this wasn’t the case since I tried it on another computer, and every other site worked fine.

Eventually I found the problem. I was doing a PHP include and instantiating an object in the very top of the file, before the doctype and html tag. I moved this into the body, and problem was fixed. These includes were just some libraries and didn’t output anything as far as I could tell, so I didn’t think it would cause any problems. But lo and behold, IE6 found another way to break.

If you have this problem, try and move any scripting code, even if it’s not outputting anything, into the body. Worked for me.