简体   繁体   中英

Detecting form focus and blur (multiple inputs)

I've searched around and haven't found a solution anywhere. Here's the situation.

I have a signup form with multiple inputs all within the form tag. How can I detect when someone focuses on the form and clicks off the form? Note* This is different than individual input focus/blurring. In this case, I want to treat the form as a whole, meaning, the blur state WILL NOT be activated when switching between various input fields within the form itself.

Can this be done? My application needs to detect the user focusing on a form, then sliding down a signupHelper. When the user clicks outside the form, the signupHelper slidesUp.

$("document").ready(function() { 

/* DETECT FORM USE */

$('#signupForm form').live( "focus", function(event) {
    if( $('#signupHelper').is(":visible") == false) $('#signupHelper').slideDown();
});

$('#signupForm form').live( "blur", function(event) {
    if( $('#signupHelper').is(":visible") ) $('#signupHelper').slideUp();
});

});

    <div id="signupForm">

<form class="signupMe">
<table cellspacing="0px">
    <tr>
        <td class="step">1</td>
        <td class="content" valign="bottom">
            Choose your username
            <input type="text" name="usernameAttempt">
    </td>

    <tr><td colspan="2" class="vSpace"></td></tr>

    <tr>
        <td class="step">2</td>
        <td class="content" valign="bottom">
            Email Address
            <input type="text" name="usernameAttempt">
        </td>
    </tr>

    <tr><td colspan="2" class="vSpace"></td></tr>

    <tr>
        <td class="step">3</td>
        <td class="content" valign="bottom">
            Password
            <input type="password" name="usernameAttempt">
        </td>
    </tr>

    <tr><td colspan="2" class="vSpace"></td></tr>

    <tr>
        <td></td>
        <td><img align="right" src="/img/signup/signup.jpg" /></td>
    </tr>

</tr><table>
</form>

</div>

Any help would be greatly appreciated! Thanks, Mark Anderson

Try out this fiddle . The key is watching all the right events. This is just a basic example of the functionality.

$('form').live('focus click', function(e){
    $('#signuphelper').show();
    e.stopPropagation(); // stop prop so it doesnt reach body
});

$('form :input:last').blur(function(){  // blur of last input in form
    $('#signuphelper').hide();
}); 

$('body').live('click', function(){ // if the event reaches body hide helper
    $('#signuphelper').hide();      
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM