Dec 24, 2009

How to highlight text box with jquery

jquery is really a very useful library.
Here is very small code to highlight your text box on focus and remove the same on blur and on unload.
It's pretty simple to add in your page

// You can use this as plugin also or save this as pluginFocus.js

jQuery.fn.focusInput = function () {
return this.each(function () {
// get jQuery version of 'this'
var $input = jQuery(this);
var $win = jQuery(window);
// capture the event
$input.focus(function()
{
$input.css({border:"2px #00CCFF solid"});
});
function remove() {
$input.css({border:"1px black solid"});
}
$input.blur(function()
{
remove();
});
$win.unload(remove);
});
};


Above code is written to use as a plugin.
To know more about to write jquery plugin visit here : writing jQuery plugins.

Call above javascript file into html page :
‹script src="pluginFocus.js" type="text/javascript" language="javascript"›‹/script›


Now to apply this to text box, we will write few lines of code :

$(document).ready(function(){
$("input:text").css({border:"1px black solid"});
$("input:text").focusInput();
});

$("input:text").css({border:"1px black solid"});
This piece of code to assign border style for all text box.

$("input:text").focusInput();
$("input:text") is to find the text box. You can use another element as well.
This is where we call the function "focusInput()", which does the magic.

HTML ( for demo only ) :

‹table cellpadding="0" cellspacing="0" border="0" width="250"›
‹tr›‹td width="130" align="left" valign="top"›Email address ‹/td›‹td›‹input type="text" name="loginId" /›‹/td›‹/tr›
‹tr›‹td colspan="2" height="15"›‹/td›‹/tr›
‹tr›‹td width="130" align="left" valign="top"›Password ‹/td›‹td›‹input type="text" name="loginId" /›‹/td›‹/tr›
‹tr›‹td colspan="2" height="15"›‹/td›‹/tr›
‹tr›‹td›‹/td›‹td›‹a href=""›Forgot password‹/a›‹/td›‹/tr›
‹tr›‹td colspan="2" height="15"›‹/td›‹/tr›
‹tr›‹td›‹/td›‹td›‹button class="rounded"›‹span›Sign in‹/span›‹/button›‹/td›‹/tr›
‹/table›

Finally you see the result.


blog comments powered by Disqus