Wednesday, July 4, 2012

Asp.Net jQuery change textbox style on focus


The jQuery library provides various options to work with Textboxes, in this post Asp.Net jQuery change textbox style on focus, we shall see on how to set a different style to a textbox which is currently focused.

We can achieve this by tracking the focus and blur events of the text box, in the focus event we add a style to the text box as follows.
$('input[type="text"]').focus(function() { $(this).addClass("FocusText") });


In the blur, we remove the style from the textbox as follows.
$('input[type="text"]').blur(function() { $(this).removeClass("FocusText") });
Add you own css class FocusText.
Just add this script and jQuery will take care of all the textboxes in the page, jQuery will track the focus & blur events of all the textboxes in the page and applied the on focus style to the textbox where the cursor is placed.

Here is a full example
<html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
    <title>TextBox</title>
    <link type="text/css"
href="Stylesheet.css"
rel="Stylesheet" />
    <script
type="text/javascript"
src="JavaScript/jquery-1.7.2.js"></script>
    <script
type="text/javascript"
language="javascript">
        $(document).ready(function() {
            $('#cmdSetFocusStyle').click(function(event) {
                event.preventDefault();
                $('input[type="text"]').focus(function() { $(this).addClass("FocusText") });
                $('input[type="text"]').blur(function() { $(this).removeClass("FocusText") });
                $('#txtName').focus();
            });        });
    </script>
</head>
<body>
    <form id="frmTextBox" runat="server">
    <div id="pageControls">
        <table>
            <tr>
                <td>Name</td>
                <td><asp:TextBox
id="txtName"
runat="server"
MaxLength="100"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Age</td>
                <td><asp:TextBox
id="txtAge"
runat="server"
MaxLength="25"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><asp:TextBox
ID="txtAddress"
runat="server"
MaxLength="200"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Phone</td>
                <td><asp:TextBox
ID="txtPhone"
runat="server"
MaxLength="20"></asp:TextBox></td>
            </tr>           
            <tr>
                <td>Email</td>
                <td><asp:TextBox
ID="txtEmail"
runat="server"
MaxLength="30"></asp:TextBox></td>
            </tr>
            <tr>
    <td&gtSet Focus Style</td>
                <td><asp:Button
ID="cmdSetFocusStyle"
runat="server"
Text="Set Focus Style" /></td>
            </tr>
  </table>
    </div>
    </form>
</body>
</html>

Search Flipkart Products:
Flipkart.com

No comments: