Reputation: 81
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?
Upvotes: 0
Views: 1350
Reputation: 8600
<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
Upvotes: 3