简体   繁体   中英

jquery - add event handler on event that takes another event as argument

I am trying to call a function scheduleAdd when the enter button is hit, but I only want it to work if an input with the id 'addSchedule' is in focus. Here's what I have:

    $('#addSchedule').focus(function(e) {
    var evt = e || window.event;  
    if(evt.keyCode == 13) {scheduleAdd};
 });

I know the code inside the .focus works, because I tried it on its own and it triggers the function scheduleAdd when the enter key is hit. How can I make this conditional on 'addSchedule' being in focus?

Also, more generally, I was wondering if there's a standard way to ascribe event handlers conditional on a second event, such as nesting .on() or something.

Thanks.

Simply the keydown event, and decide to do something or nothing based on whether the current element has the specified id:

$(document).on("keydown", function() {
    if (!$("#addSchedule").is(":focus")) return;
    // do stuff
});

Alternatively you can also check for the identity of the focused element with document.activeElement.id === "addSchedule" if you don't mind that's not enough jQuery. ;-)

Demo on fiddle

HTML:

<form>
  <input id="addSchedule" type="text" />
</form>

Javascript:

 $('#addSchedule').keydown(function (event) {
     if (event.which == 13) {
         event.preventDefault();    // This will prevent the page refresh.
         scheduleAdd();
     }
     function scheduleAdd() {
         alert("Add the schedule");
     }
 });

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