3

How can I trigger the backspace key event in jQuery?

The following example isn't working:

var e = jQuery.Event("backspace", { keyCode: 8 });
$("#myarea").trigger( e );
Diogo Cardoso
  • 21,637
  • 26
  • 100
  • 138

2 Answers2

10

You can't actually trigger it.

You could, for example, remove the last character from a certain input, but you can't trigger the actual key.

Example:

var str = $('#input').val();
$('#input').val(str.substring(0, str.length - 1));
skimberk1
  • 2,064
  • 3
  • 21
  • 27
2

You can't trigger the backpace key.

With the jquery caret plugin, you can simulate the press on the backspace key by removing the correct characters.

backspace = function (element_name) {
    var element = $(element_name);
    var caret_pos = element.caret();
    var new_val = element.val().substr(0, caret_pos - 1) + element.val().substr(caret_pos);
    element.val(new_val);
    if (caret_pos > 0) {
        element.caret(caret_pos - 1);
    }
};

See this jsfiddle (you might need to change the caret plugin source)

leszek.hanusz
  • 5,152
  • 2
  • 38
  • 56