Sometimes, we want to prevent select on input text field with JavaScript.
In this article, we’ll look at how to prevent select on input text field with JavaScript.
How to prevent select on input text field with JavaScript?
To prevent select on input text field with JavaScript, we can set the input’s selectionStart
property to the value of the input’s selectionEnd
property.
For instance, we write:
<input>
to add an input.
Then we write:
const input = document.querySelector('input');
input.onselect = (e) => {
e.target.selectionStart = e.target.selectionEnd;
}
to select the input with querySelector
.
Then set the input.onselect
property to a function that sets e.target.selectionStart
to e.target.selectionEnd
to set the selection range to length 0 to prevent selection.
Conclusion
To prevent select on input text field with JavaScript, we can set the input’s selectionStart
property to the value of the input’s selectionEnd
property.