Here is the code for a universal function in handling form input helper text. The last value will default to 'default'. This was a class name we chose to allow us to lighten the color of the helper text only.
/**
* Handles add/removing helper text for form input fields
*
* @param selector Jquery selector value of element to add helper to
* @param helperText Text to be placed in the input if input has no value
* @param css Css class to be added when helper text is set
*/
function form_helper_text( selector, helperText, css ) {
$(document).ready(function(){
// set css default value if none provided
css = typeof( css ) != 'undefined' ? css : 'default';
// select form element and if helper text is submitted replace with ''
var form = $( selector ).parents( 'form:first' );
$( form ).submit(function(){
if( $( selector ).val() == helperText ) {
$( selector ).val( '' );
}
});
// set action when field is not selected (add helper text)
$( selector ).blur(function(){
if( $(this).val() == '' ) {
$(this).addClass( css );
$(this).val( helperText );
}
});
// set action when field is selected (remove helper text)
$( selector ).focus(function(){
if( $(this).val() == helperText ) {
$(this).val( '' );
$(this).removeClass( css );
}
});
// trigger blue action to add helper text
$( selector ).trigger( 'blur' );
});
}
3 comments:
I like it, but shouldn't it really be a plugin for jQuery so you could use it like:
$(".my-selector").form_helper_text("my helper text","className");
like: http://github.com/m3talsmith/jquery-input-helpers/blob/master/jquery.input-helper.js
You are correct, I have actually since made it a plugin but have not updated this post. I will update the post soon. In addition I have reduced some efficiencies with the form_helper_text function.
Right now its bundled with a newWindow helper. So I will just throw that in as well. We are using js to open in a new window since the target attribute is not supported in xhtml strict.
Post a Comment