简体   繁体   中英

How to call a function on onfocus event in jquery

Actually my question is something different.

I called a function on .focus event of the first element of form in my tiny box like below.

        $(".tbox :input:visible:enabled:first").focus(function () {
            tabIndexForm();
         });

It is working perfectly but this is replacing my own function called on onfocus event on the first element of form which I have set manually. how to do this. my form is:

 <form name="exampleform">
  <input type="text" name="a" onfocus="somefunction();"/>
  <input type="text" name="b"/>
  </form>

Now when I open the tiny box the tabIndexForm function calls perfectly but somefunction() is not working because I think the tabIndexForm replaces this function. How to upldate the following code to work both.

         $(".tbox :input:visible:enabled:first").focus(function () {
            tabIndexForm();
         });

Important: I can not call "somefunction()" in tinybox.js because this is common for all tiny boxes.

The 'focus' function /binds/ an event handler to the element.

Try the new 'on' function, which /adds/ an event handler.

$(".tbox :input:visible:enabled:first").on('focus', function () {
        tabIndexForm();
});

EDIT first try doesn't work.

That should work better:

$(".tbox").on('focus', ":input:visible:enabled:first", function () {
        tabIndexForm();
});

That way the event handler is not attached to the element, so it doesn't overwrite the old one.

This should work:

var elem = $(".tbox :input:visible:enabled:first");
var oldFunc = elem[0].onfocus;
elem.focus(function () {
    if(typeof oldFunc == 'function') oldFunc.call(elem[0]);
    tabIndexForm();
});

Check this demo : http://jsfiddle.net/8JbvY/

Remove the onfocus property from your element:

<form name="exampleform">
  <input type="text" name="a"/>
  <input type="text" name="b"/>
</form>

And change your javascript to:

$(".tbox input[name='a']").focus(somefunction);

$(".tbox :input:visible:enabled:first").focus(function () {
     tabIndexForm();
});

This is also a neater way of dealing with your event handlers as you are keeping the logic in one place.

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