Javascript sending key codes to a <textarea> element

浪尽此生 提交于 2019-11-29 08:46:44

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?

Try this:

$(document).ready(function() {
var $comment = '';
$('#first').keyup(function() {
    $comment = $(this).val();
    $comment = $comment.replace(/<\/?[^>]+>/g,"").replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />'); // this strips tags and then replaces new lines with breaks
    $('#second').html( $comment );
});
});

Working demo: http://jsbin.com/ivulu

Or if you don't want to sanitize the data: http://jsbin.com/oposu

$(document).ready(function() {
var $comment = '';
$('#first').keyup(function() {
    $comment = $(this).val();
    $('#second').html( $comment );
});
});

Here's an example: apparently you add to the textarea's value property.

The keydown event is not responsible for actually updating the value of the textbox. Your code works just fine, but since you don't have an event handler on the second textbox, it doesn't look like anything happens. If you want to update the text in the textbox, change its value, as demonstrated by jyoseph.

If you need to trigger the event as well (for some reason), your code as written will do that.

You can't just "create" events on the client's machine. Can't you imagine the potential security vulnerabilities? It's a no-brainer. The only thing you can do is fire an event handler...

textarea2.onkeydown();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!