Accessibly autopopulating text input fields with jQuery

Roger Johansson over at the 456 Berea Street blog post an awesome post a little over a year ago about accessibly using Javascript to autopopulate a text input field in an HTML form using the title attribute of the <input/> element.

I’ve been using this for a while at work and in side-projects, an since I’m a dedicated fan of the jQuery framework, I decided to re-write his agnostic version for jQuery and share it with the world.

The Markup (XHTML):

<input type="text" class="populate" name="search" value="" />

The Javascript:

$(document).ready(function(){
	$("input.populate").each( function(){
		if ( $(this).val() == "" ) {
			$(this).val( $(this).attr("title") );
		}
	});
	$("input.populate").focus(function(){
		if ( $(this).val() == $(this).attr("title") ) {
			$(this).val("");
		}
	});
	$("input.populate").blur(function(){
		if ( $(this).val() == "" ) {
			$(this).val( $(this).attr("title") );
		}
	});
});

I’ll create an online demo soon enough.

This is a quick, light-weight way to add some great user-experience and flavor to your UI. If you’re not a jQuery fan, definitely implement Roger’s accessible autopopulating technique.

3 Comments

  1. Rob Wilkerson says…

    I like this. I guess I either missed or forgot about Roger’s article, but this is simple and elegant with less text hard coded throughout the page. Can’t beat that. Think I’ll start using this myself.

  2. Andy says…

    Thanks, Rob. Another option we thought of was just taking any input that has the title attribute set behave this way since adding the title attribute to an input element is pretty rare:

    	$(document).ready(function(){
    
    		$("input[title!='']").each(function(){
    			$(this).each( function(){
    				if ( $(this).val() == "" ) {
    					$(this).val( $(this).attr("title") );
    				}
    			});
    			$(this).focus(function(){
    				if ( $(this).val() == $(this).attr("title") ) {
    					$(this).val("");
    				}
    			});
    			$(this).blur(function(){
    				if ( $(this).val() == "" ) {
    					$(this).val( $(this).attr("title") );
    				}
    			});
    		});
    
    	});
  3. Rob Wilkerson says…

    True, but I know I do it in many cases where I’m sure that the content will likely extend beyond what the input can contain. It’s a nice way of showing the entire content without violating the design, IMO. For that reason, the latter option may not work for me. I’ll have to think about the edge cases, though; it seems like it might work anyway, since it keys on an empty value to trigger any change of the value.

RSS feed for comments on this post. TrackBack URL

Leave a Comment

January 27, 2009

Filed in Uncategorized

There are 3 comments »


« Back to the Blog