Basit
Basit

Reputation: 39

Prevent select on input text field using Class and Tag Name

I am trying to prevent selection on an input field with the following:

considerations

  1. Prevent selection using mouse
  2. Prevent selection using keyboard (including Ctrl+A, shift+arrows)
  3. Allow focusing into field using keyboard and mouse

So far I have tried these things: The id is work well but i want to tag name.

HTML

<p class="noselect">
 Unselectable text.
 <input class="my_input" type="text" value="Try to select me!">
</p>

JS

var inp = document.getElementByClassName('my_input');
inp.addEventListener('select', function() {
    this.selectionStart = this.selectionEnd;
}, false);   

Upvotes: 0

Views: 185

Answers (1)

prophet1906
prophet1906

Reputation: 123

There are minor corrections in given code snippet.

  1. getElementsByClassName instead of getElementByClassName
  2. getElementsByClassName returns array of dom elements with given class so selecting 1st one using inp[0].

var inp = document.getElementsByClassName('my_input');
inp[0].addEventListener('select', function() {
  this.selectionStart = this.selectionEnd;
}, false);

Upvotes: 1

Related Questions