Detect which form input has focus using JavaScript or jQuery

前端 未结 9 2560
灰色年华
灰色年华 2020-11-29 09:20

How do you detect which form input has focus using JavaScript or jQuery?

From within a function I want to be able to determine which form input has focus. I\'d like

9条回答
  •  天涯浪人
    2020-11-29 09:39

    I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:

    function getSender(field) {
        switch (field.id) {
            case "someID":
            case "someOtherID":
                return 1;
            break;
            default:
                return 0;
        }
    }
    
    function doSomething(elem) {
        if (getSender(elem) == 1) {
           // do your stuff
        }
      /*  else {
           // do something else
        }  */
    }
    

    HTML Markup:

    
    
    
    

    The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).

    -Tom

提交回复
热议问题