jQuery multiple events to trigger the same function

后端 未结 11 1301
青春惊慌失措
青春惊慌失措 2020-11-22 04:45

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do the

11条回答
  •  独厮守ぢ
    2020-11-22 05:26

    If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).

    It sounds like what you actually want is something like this:

    $('#ValidatedInput').keydown(function(evt) {
      // If enter is pressed
      if (evt.keyCode === 13) {
        evt.preventDefault();
    
        // If changes have been made to the input's value, 
        //  blur() will result in a change event being fired.
        this.blur();
      }
    });
    
    $('#ValidatedInput').change(function(evt) {
      var valueToValidate = this.value;
    
      // Your validation callback/logic here.
    });
    

提交回复
热议问题