0

I am trying to prevent the backspace key from going to the previous page. I have Javascript code to prevent that, and it works... Unless the focus is inside of the textbox element. The problem is that the particular textbox is Read-Only. If I remove the Read-Only attribute, then all is well, I can press backspace all I want with the focus in the textbox and it will not go to the previous page, but I need the attribute set.

Below is the code preventing the backspace key from going to the previous page, but allowing it to be used inside of Non Read-Only input fields.

        $(document).keydown(function (e) {
            if (e.keyCode == 8 && e.target.tagName != 'INPUT' && e.target.tagName != 'TEXTAREA') {
                e.preventDefault();
            }
        });

The expected outcome is to be able to focus the Read-Only textbox, and press the backspace key and the application NOT go back to the previous page.

RJS
  • 81
  • 1
  • 5
  • This isn't exactly what you want, but in case you don't find a solution, you may be able to [use the `OnBeforeUnload` event to prevent users from accidentally navigating away](https://stackoverflow.com/questions/6825097/warn-user-when-navigating-from-page-with-unsaved-changes). (Another option is to merely *simulate* a text-box being read-only, style it to look read-only, and listen to the onchange event, resetting the value to the fixed value.) – Conspicuous Compiler Apr 17 '19 at 16:35
  • Add `e.target.attributes["readonly"]` check. Meanwhile, the question has nothing to **ASP.NET**. – Alex Kudryashev Apr 17 '19 at 18:14

1 Answers1

0

Just check if the field is readonly:

$(document).keydown(function (e) {
    if (
       e.keyCode == 8 &&
       (e.target.tagName != 'INPUT' || e.target.readOnly) && 
       e.target.tagName != 'TEXTAREA') {
                e.preventDefault();
    }
});
Lesmian
  • 3,932
  • 1
  • 17
  • 28