Search This Blog

Wednesday, 19 June 2013

Highlight a textbox when focused using JavaScript

Refer below code, where we attach an event dynamically at the time of page loads

<script language="javascript" type="text/javascript">
    function fnTXTFocus(varname) {

        var objTXT = document.getElementById(varname)
        objTXT.style.borderColor = "Red";

    }

    function fnTXTLostFocus(varname) {
        var objTXT = document.getElementById(varname)
        objTXT.style.borderColor = "White";
    }

    function fnOnLoad() {
        var t = document.getElementsByTagName('INPUT');
        var i;
        for (i = 0; i < t.length; i++) {
            if (t[i].type == "text") {
                t[i].attachEvent('onfocus', new Function("fnTXTFocus('" + t[i].id + "')"));
                t[i].attachEvent('onblur', new Function("fnTXTLostFocus('" + t[i].id + "')"));
            }
        }
    }
</script>
<body onload="fnOnLoad()">
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    UserName ::
                </td>
                <td>
                    <asp:TextBox ID="txtUN" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password ::
                </td>
                <td>
                    <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Confirm Password ::
                </td>
                <td>
                    <asp:TextBox ID="txtCpwd" runat="server"></asp:TextBox>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>

The above JavaScript:

Finds the list of textboxes and stores it in an array.
Attaches the OnFocus and OnBlur events to each textbox in the list.

So now, whenever a textbox gets/loses focus, the assigned function will fire.


You can download a sample from here

No comments:

Post a Comment