Javascript sending key codes to a <textarea> element

前端 未结 5 998
说谎
说谎 2020-12-18 14:58

I can\'t figure out how to trigger a keydown event on a textarea element, e.g. imagine i have two textarea elements and when i type something in the first one, I want the se

5条回答
  •  离开以前
    2020-12-18 15:20

    The event is sent, the browser just doesn't react to it (i.e., put characters in the textarea)

    Not all browsers (that I know of) allow you to dispatch events, not just trigger them. But even doing that is far from perfect

    // Gecko only
    $("#first").keypress(function(event)
    {
      var evt = document.createEvent('KeyEvents');
      evt.initKeyEvent(
          event.type
        , event.bubbles
        , event.cancelable
        , event.view
        , event.ctrlKey
        , event.altKey
        , event.shiftKey
        , event.metaKey
        , event.keycode
        , event.charCode
      );
      $('#second')[0].dispatchEvent( evt );
    });
    

    Try this example and you'll see what I mean by how it's far from perfect. Basically, the way to do what you're asking is also the way you say you can't - by value.

    However, you can pass custom data along with the event, which leads to a solution that looks like this

    $("#first").bind( 'keyup change', function(event)
    {
      $('#second').trigger( 'mimic', $(this).val() );
    });
    $("#second").bind( 'mimic', function( event, value )
    {
      $(this).val( value );
    })
    

    Is that good enough?

提交回复
热议问题