I am trying to prevent selection on an input field with the following considerations
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
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.
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.
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.
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.
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!" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With