Definitive way to trigger keypress events with jQuery

后端 未结 10 2314
不知归路
不知归路 2020-11-22 00:33

I\'ve read all the answers on to this questions and none of the solutions seem to work.

Also, I am getting the vibe that triggering keypress with special characters

相关标签:
10条回答
  • 2020-11-22 00:52

    console.log( String.fromCharCode(event.charCode) );

    no need to map character i guess.

    0 讨论(0)
  • 2020-11-22 00:53

    If you want to trigger the keypress or keydown event then all you have to do is:

    var e = jQuery.Event("keydown");
    e.which = 50; // # Some key code value
    $("input").trigger(e);
    
    0 讨论(0)
  • 2020-11-22 00:58

    In case you need to take into account the current cursor and text selection...

    This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

    I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

    1. On focus, save the lastFocus.element
    2. On blur, save the current text selection (start and stop)

      var pos = element.selection('getPos')
      lastFocus.pos = { start: pos.start, end: pos.end}
      
    3. When a button on the my keypad is pressed:

      lastFocus.element.selection( 'setPos', lastFocus.pos)
      lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
      
    0 讨论(0)
  • 2020-11-22 01:00

    If you're using jQuery UI too, you can do like this:

    var e = jQuery.Event("keypress");
    e.keyCode = $.ui.keyCode.ENTER;
    $("input").trigger(e);
    
    0 讨论(0)
提交回复
热议问题