1

I have written below lines of code for blocking users to enter some values in textbox:

$(".block-keypress").keypress(function(e){
  return false;
});

It is working fine but backspace is not blocked.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nida
  • 1,672
  • 3
  • 35
  • 68
  • 5
    Why not just set the field as `readonly`? No JS required – Rory McCrossan Oct 26 '17 at 10:03
  • what about the read-only value on the textbox if you want users don't enter any value? – Zander Oct 26 '17 at 10:03
  • Possible duplicate of [JavaScript listener, "keypress" doesn't detect backspace?](https://stackoverflow.com/questions/4843472/javascript-listener-keypress-doesnt-detect-backspace) – Walk Oct 26 '17 at 10:03
  • Due to an important reason i cannot set the textbox to read only – Nida Oct 26 '17 at 10:05
  • not sure why you are wanting to stop them entering, possibly use the disabled attribute? – Anduril Oct 26 '17 at 10:07
  • @Nida and what is that important reason? You can set and unset `readonly` in javascript when needed. Anyway, check linked question above, it has an answer. – Walk Oct 26 '17 at 10:07
  • If you don't want users to enter or modify values at all, then it seems that a form input wasn't the way to go with this. – David Oct 26 '17 at 10:08

1 Answers1

4

try with new code

use keydown instead of keypress

$(".block-keypress").keydown(function(e) {
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="block-keypress" value="test">
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
  • no it doesn't if you already have a value set suppose. Then try this out backspace will still work. – Manish Oct 26 '17 at 10:09