Chuck
Chuck

Reputation: 23

JQuery: How do I hide a DIV when textbox is out of focus?

This is the code I have:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtInsertComments" CssClass="expanding" runat="server" AutoPostBack="false" TextMode="MultiLine"></asp:TextBox>
    </div>
        <div id="commands">
            <table cellpadding="0" cellspacing="0" width="400px" id="tblCommands">
                <tr>
                    <td style="width: 50%; text-align: center;">
                        <asp:LinkButton ID="lnbInsertRes" runat="server" CommandName="Insert" Font-Underline="false">Insert</asp:LinkButton>
                    </td>
                    <td style="width: 50%; text-align: center;">
                        <asp:LinkButton ID="lnbCancelRes" runat="server" CommandName="Cancel" Font-Underline="false">Cancel</asp:LinkButton>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
    <script type="text/javascript">
        $(function()
        {
            $("#commands").hide("normal");

            $("textarea[id$=txtInsertComments]").focus(function()
            {
                $("#commands").show("normal");
            });

        });
    </script>
</html>

First, when this page is loading, the div #command is loaded very quick and then disappears. I need the div to remain hidden until the textbox txtInsertComments control is clicked or gets focus.

Second, when the user click out of the textbox txtInsertComments or that the textbox lost focus, the div #command is still there and not hidden.

Any help is appreciated.

Upvotes: 2

Views: 5130

Answers (3)

James Goodwin
James Goodwin

Reputation: 7406

You can use CSS to hide the #command DIV until you want to show it:

<div id="commands" style="display:none">

Then use blur/focus to show/hide the #commands DIV:

$('#txtInsertComments').blur(function() {
    $("#commands").hide()
}).focus(function() {
    $("#commands").show()
});

Upvotes: 4

Jimmeh
Jimmeh

Reputation: 2872

$(document).ready(function() {
    $('#<%=txtInsertComments.ClientID%>').blur(function() 
       { $("#commands").hide() });
    $('#<%=txtInsertComments.ClientID%>').focus(function() 
       { $("#commands").show() });
});

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163308

Set display:none initially on #commands.

<div id="commands" style="display:none">....

For losing focus, just use the blur event:

$( el ).blur( function(){...} );

Upvotes: 1

Related Questions