0

I'm trying to prevent user input into a textarea with Javascript.

Why doesn't this work?

$("textarea").on("input", function (e) {
  console.log("returning"); //This prints
  e.preventDefault();
  return false;
  //Even though this code runs when text is inputed into the textarea, it still doesn't prevent user input. Shouldn't returning false do that?
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Wyatt
  • 493
  • 7
  • 18
  • Duplicate of https://stackoverflow.com/questions/32298064/preventdefault-not-working-in-on-input-function – Bsalex Oct 31 '17 at 23:00
  • Try `keydown` instead of input – emil Oct 31 '17 at 23:01
  • The input event fires _after_ there has been input to a control. Quoting from https://developer.mozilla.org/docs/Web/Events/input _ -- "The DOM input event is fired synchronously when the value of an , – Stephen P Oct 31 '17 at 23:03
  • Possible duplicate of [.preventDefault() not working in on.('input', function{})](https://stackoverflow.com/questions/32298064/preventdefault-not-working-in-on-input-function) – Stephen P Oct 31 '17 at 23:07

3 Answers3

1

You are preventing the default action of a noncancelable event, not the input. You need to disable the input to get the desired result, disable the input programatically:

$("textarea").prop("disabled", (1 === 2)/*some condition*/);
Rafael
  • 7,605
  • 13
  • 31
  • 46
0

Input Event : The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.

Use keydown instead of input for this purpose :

$('textarea').keydown(function(e) {
  console.log("returning"); //This prints
  e.preventDefault();
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea></textarea>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

If you really don't want a cursor to even appear over your Element, then you should not use a textarea or input at all, but if you must, you can do this:

<textarea readonly='readonly'></textarea>

or

$('textarea').attr('readonly', 'readonly');
StackSlave
  • 10,613
  • 2
  • 18
  • 35