Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent select on input text field

Tags:

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

  • Prevent selection using mouse
  • Prevent selection using keyboard (including Ctrl+A, shift+arrows)
  • Allow focusing into field using keyboard and mouse

So far I have tried these things:

CSS

I have attempted the using the following class

.unselectable {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Result: selection still possible

I have also tried below with no success:

$("#my_field").attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', 
           '-webkit-user-select':'none',
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

Javascript

I tried the below

$( "#my_field" ).select(function(e) {
        console.log("Select called");
        e.preventDefault();
});

Result: console printed the message, however the select still works

Thanks for your help

like image 608
user2636664 Avatar asked Mar 23 '15 22:03

user2636664


People also ask

How do I block text selection in HTML?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.

How do you prevent input input field?

To prevent user from typing in text field without disabling the field with HTML, we can add the readonly attribute to the input. to stop users from enter text into the input without making it look disabled.

How do you restrict input fields in HTML?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I disable a text box?

We can easily disable input box(textbox,textarea) using disable attribute to “disabled”. $('elementname'). attr('disabled','disabled'); To enable disabled element we need to remove “disabled” attribute from this element.


1 Answers

It can be done by setting the element's selectionStart to selectionEnd on select event:

var inp = document.getElementById('my_input');

inp.addEventListener('select', function() {
  this.selectionStart = this.selectionEnd;
}, false);
<input id="my_input" type="text" value="Try to select me!" />
like image 57
Hashem Qolami Avatar answered Oct 13 '22 01:10

Hashem Qolami