Pages

Friday, August 5, 2011

Highlighting Active Text Input Fields (HTML forms/Javascript)

Ever wondered how to "Highlight" your current entry field in a web form? Javascript allows you to do this by simply adding the script below inside the <head> </head> section of your web page.

<script type="text/javascript">
function setXY(x) {
  document.getElementById(x).style.background="#FFFF00";
}
</script>

Within the <body>… </body> section, you can simply attach your script to any <input> event attribute. In this example, we use onfocus and onmouseover.

For the entry field:

<input type='text' ID="INP" name="input_1" onfocus='setXY(this.id)' onblur='setLo(this.id)' >

NOTE: Since the script uses the getElementById javascript method, it is very important that you assign a unique "ID" attribute to your input tags. Without it, this simply won’t work.

You can be creative by combining several techniques to create "highlight on" and "highlight off" effect by simply reversing the highlight color back to the original.

In the sample code below, we use setHi(x) to set highlight and setLo(x) to unset it. Here’s how you can use this script on a form input element with event attributes:


<html>
<head>

<script type="text/javascript">
function setHi(x) {
  document.getElementById(x).style.background="#FFFF00"; 
}

function setLo(x) {
  document.getElementById(x).style.background="#FFFFFF"; 
}
</script>

</head>
<body>

<B>sample text input</B><BR><BR>
<input type='text' ID="INP_1" name="input_1" onfocus='setHi(this.id)' onblur='setLo(this.id)' > <BR><BR>

</body>
</html>


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.