0

I have input and a button. On that button click, JavaScript should be triggered. I need that input to be restricted from typing, pasting, deleting...

When I set disabled tag to it, JavaScripts that interact with it don't work.

<input disabled type="text" value="NOT BE CHANGED">
<button>Trigger some javascript</button>

Try it on JSiddle

How else can input be restricted from typing, pasting, deleting... but still be interactive with JavaScripts?

5
  • 1
    enable it, copy, then disable it again. Commented Mar 5, 2020 at 23:42
  • 2
    Have you tried the readonly attribute? Commented Mar 5, 2020 at 23:46
  • Also to set the value of a <textarea>, set the value property, not textContent. Commented Mar 5, 2020 at 23:47
  • May be do not to use textarea but a div/label instead. Otherwise blur on focus or transparent div above it. Commented Mar 5, 2020 at 23:54
  • @bestinamir I've tried to use paragraph but I need input for PHP script. Commented Mar 6, 2020 at 13:29

1 Answer 1

3
<input type="text" class="id-format" id="id-format" value="SHALL NOT BE CHANGED">

JQuery: Call on your <input> id field with JQuery and use the .prop() function to set the readonly attribute to true.

$('#myID').prop('readonly', true);

Pure JS: Call on input id and add setAttribute() function to add the readonly attribute and set it to true.

document.getElementById("id-format").setAttribute('readonly', true);

OR set your attribute inline within your input tag

<input type="text" class="id-format" id="id-format" readonly="true" value="SHALL NOT BE CHANGED">

The reason disabled does not work: If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. Do not set the attribute to true, as this will suggest you can set it to false to enable the element again, which is not the case.

readonly : Type: boolean If set to true, then the user cannot change the value of the element. However, the value may still be modified by a script.

JS Fiddle Here: https://jsfiddle.net/72g6hpfc/

info:

disabled - https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/Attribute/disabled

readonly - https://developer.mozilla.org/en-US/docs/Archive/Mozilla/XUL/Attribute/readonly

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, very nice explanation and showed me all ways to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.