Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger backspace on a textfield?

Say I have this:

<textarea id="myarea">Hello</textarea>

How would i trigger backspace on that textarea possibly using trigger() and key codes. The code for backspace is 8. And i am not looking for this:

$('#myarea').val( $("myarea").val().slice(0,-1) );

I need to simulate someone actually pressing the 'backspace' key on their keyboard. Thanks

like image 262
odle Avatar asked Aug 03 '11 02:08

odle


3 Answers

You can create a keydown event:

var e = jQuery.Event("keydown", { keyCode: 20 });

Then trigger it in your textarea:

$("#myarea").trigger( e );

Update:

After doing some more research and testing, I realize that this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keydown event, it does not replicate the user going into the element and pressing that key.

To simulate the user going into that textbox and pressing that key, you would have to create a dispatch event

The dispatch event is also not globally supported. Your best bet would be to trigger the keydown event and then update the text area as intended.

like image 151
rkw Avatar answered Nov 01 '22 14:11

rkw


I found this:

http://forum.jquery.com/topic/simulating-keypress-events (answer number 2).

Something like this should work, or at least give you an idea:

<div id="hola"></div>

$(function(){
    var press = jQuery.Event("keyup");
    press.ctrlKey = false;
    press.which = 40;

    $('#hola').keyup(function(e){
        alert(e.which);
    })
   .trigger(press); // Trigger the event
});

Demo: http://jsfiddle.net/qtPcF/1/

like image 45
Jose Adrian Avatar answered Nov 01 '22 16:11

Jose Adrian


You shouldn't be forcing key events in js. Try simulating the character removal instead.

const start = textarea.selectionStart - 1;
const value = textarea.value;
const newValue = value.substr(0, start) + a.substr(start);
textarea.value = newValue;

Or if you just want the event, instead call the handler directly, rather than forcing the event. This is too hacky.

like image 1
Gibolt Avatar answered Nov 01 '22 14:11

Gibolt