Categories
JavaScript Answers

How to prevent select on input text field with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *