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
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();
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.