How to prevent selection on an input text field with JavaScript?

Estimated read time 1 min read

To prevent selection on an input text field with JavaScript, you can use the onselectstart property or the selectstart event.

Here’s an example using the onselectstart property:

document.querySelector("input").onselectstart = function() {
    return false;
};

In this example, we use querySelector to select the input element and then set its onselectstart property to a function that returns false. This will prevent selection of the text in the input field.

Here’s an example using the selectstart event:

document.querySelector("input").addEventListener("selectstart", function(event) {
    event.preventDefault();
});

In this example, we use querySelector to select the input element and then add an event listener for the selectstart event. The function passed to the event listener calls preventDefault to prevent the selection of the text in the input field.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply