Arpita Dutta Arpita Dutta -4 years ago 128
jQuery Question

Prevent backspace from deleting in Jquery

I have a text box. When a user presses the backspace button, I want to prevent the backspace from deleting text and to give a specific alert e.g. "Do you want to delete"? along with two buttons. Only when the user confirms the delete operation, the subsequent backspace button clicks would delete the texts.

I have written the below code. Though it works fine. but it is not able to prevent the backspace from deleting the text. Can anyone help me out in this?

$("#txtCustNameSHP").keyup(function (e) {
var key = event.keyCode || event.charCode;
if (keypresscount == 0 && key == 8 || key == 46) {
title: "Confirmation",
msg: "Do you want to delete the Shipper?",
button1Text: "YES",
button2Text: "NO",
button1Click: function () {
//$("#" + txtCustCodeSHP).text("");
button2Click: function () {
return false;
width: "350px",
height: "100px"

Answer Source

issue 1: you should use keydown instead of keyup because keyup will be triggered after deletion already done

issue 2: your event is e not event

$("#txtCustNameSHP").keydown(function (e) {
  var key = e.keyCode || e.charCode;
  if (key == 8 || key == 46) {
<script src=""></script>
<input id="txtCustNameSHP" value="foobar" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download