Disable user from typing in input

Quazey :

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?

dale landry :
<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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34477&siteId=1