开发者

JQuery: .focus() event on whole form? How to?

consider the following HTML:

<form ....>
   <textarea>....</textarea
   <input .... />
</form>

Now I want to show a help section when开发者_运维知识库 the user is focused on ANY of the form elements. When the focus is gone the help information should too.

My idea was this:

$("form").focus(function(){...});
$("form").unfocus(function(){...});

But it doesn't seem to work. Any ideas? Thanks a lot for your help!

Tom

Addition: Thank you all a lot, it works. I used lonesomeday's solution, but there is another problem with my animations:

$('form').delegate(':input', 'focus', function() {

    $("#eintrag").animate({"height": "160px"}, 500)
    $("#header").animate({"height": "200px"}, 500)
    $("#container").animate({"margin-top": "240px"}, 500)
    $(".show").animate({"opacity": "0"}, 500)
    $(".hide").animate({"opacity": "1"}, 500)
    $("#header_links>p").animate({"opacity": "0"}, 500)

}).delegate(':input', 'blur', function() {

    $("#eintrag").animate({"height": "20px"}, 500)
    $(".show").animate({"opacity": "1"}, 500)
    $("#container").animate({"margin-top": "150px"}, 500)
    $(".hide").animate({"opacity": "0"}, 500)
    $("#header_links>p").animate({"opacity": "1"}, 500)
    $("#header").animate({"height": "110px"}, 500)

});

This means that I get the animation each time I change focus within the form. How do I change this?


Hmmm I would just find all the input elements and bind against them e.g.

$(function() {
    $( '#form_id' ).find('input').focus(function() {

        //your function

    });

  $( '#form_id' ).find('input').blur(function() {

        //your function

    });

});


try using $(":input") (mind the colon)

also the opposite event of focus is blur, not unfocus


The problems:

  1. The inverse of focus is blur. unfocus unbinds a focus handler.
  2. You're binding to the form element, whereas it is the elements within the form (in jQuery, these can be found with :input) that receive focus.

The nicest way to do this is with delegate:

$('form').delegate(':input', 'focus', function() {
    $('#help').show();
}).delegate(':input', 'blur', function() {
    $('#help').hide();
});

This is the quickest way to handle this.

See jsFiddle example.


see focus(). It is not intended to be used with 'form' elements, but with input, textarea... etc

Try

$("form input").focus(function(){...}).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜