Prevent selection inside an input element
I want to do the following
- Prevent selection of text inside an input element
- Don't show the carrot cursor inside the entrance
I can't just blur the input with a tap, the focus must remain on the input. There is probably a way to do this only in IE, I would of course have a cross-browser solution, but badly settle for IE (or FF) only solution.
Here's a demo page where you can see why I might need this feature:
http://programmingdrunk.com/current-projects/dropdownReplacement/
if you click the dropdowns on the first line on the page, you will see carrots inside the dropdown menu, which looks funny. (this won't happen in chrome, but it will in FF or IE)
a source to share
A bit hacky, but:
onclick="this.selectionStart=this.selectionEnd=-1;"
onselect="this.selectionStart=this.selectionEnd=-1;"
Seems to work in Firefox (3.6.3).
Provide us with the whole service and hide it from HTML though ( attachEvent
magic) .. And don't tell anyone, I suggested it :)
a source to share
You can disable text selection in some non-IE browsers with user selection CSS.
-webkit-user-select:none;
-k-user-select:none;
-moz-user-select:moz-none;
user-select:none;
Not sure about IE.
As for the effect you are trying to achieve, how to make the input invisible and have a div on top of the input that displays the value of the input?
If you need to change the value on the input, the click event on the div will direct focus to the input, and the keypress event will update the div.
Haven't tried it but it looks like it should work.
EDIT:
Use CSS to display invisible input to preserve tab functionality.
(Assumes background is #FFF)
#myInput {
border-width:0;
color:#FFF;
background:#FFF;
outline:0;
}
a source to share
I am using the following function in my code, it is not JQuery, but it is quite easy to convert:
function disableSelection(elm) {
// Disable the selection of `elm` - should work for all major browsers except Opera
// which doesn't seem to allow disabling selections unless the mousedown
// events etc are cancelled as far as I know
// Disable the select start event
elm.onselectstart = function() {
return false
}
// Disable in IE - see http://msdn.microsoft.com/en-us/library/ms534706(VS.85).aspx
elm.unselectable = "on"
// Disable in Mozilla - see https://developer.mozilla.org/en/CSS/-moz-user-select
elm.style.MozUserSelect = 'none'
// Disable Safari/Chrome
// See http://help.dottoro.com/lcrlukea.php
elm.style.webkitUserSelect = 'none'
// Disable in other browsers
elm.style.userSelect = 'none'
// Display a normal cursor
elm.style.cursor = "default"
}
a source to share