Cross-browser: Different Behaviors For Disabled Input Fields (the Text Can/can't Be Copied)
Solution 1:
Change your field from disabled
to readonly
. That is the correct attribute for the behaviour you want.
Don't waste time hacking a javascript solution together as it will be even more flaky than the minor differences in browser behaviour.
If the issue is that you want your readonly fields to look like disabled fields, it's fairly easy to style an input with a readonly
attribute set. You don't need to change behaviour to change appearance.
input[readonly] {
background: #EEE;
color: #666;
border: solid 1px#CCC;
}
<inputreadonlyvalue="I am readonly">
Solution 2:
I tried to use user-select
in an input but it can't prevent selecting of text to it. Even wrap it to a div
with a user-select: none
style still not work. It's only work for (I think) non-focusable element like div, span, etc.
However, right now I think user-select: none
is the only better option if you want to ensure that user won't copy the text from the page even in many different browsers (check user-select browsers compatibility). So I would suggest, create a component that something like this:
<input *ngIf="!isDisabled"value="model" /><div *ngIf="isDisabled"style="user-select: none">{{model}}</div>
Caveat: You have to styled the div
to be more like a disabled input.
Solution 3:
There is nothing wrong with doing this when you disable a form control.
<input type="text" disabled readonly value="is disable">
or
<input type="text" disabled="disabled"readonly="readonly" value="is disable">
However, that may not produce consistent behavior as it pertains to copying text (after selecting it).
An Imperfect JavaScript Way:
I have not used a select
type event in a while, but I suggest toggling the ability to select the text. You might also play with the focus
and blur
events.
External CSS Style Sheet:
.preventSelection {user-select: none} // IE 10+
Quick and Dirty Event Handler:
functionpreventDisabledControlTextCopy(e)
{
// blah, blah, blahif (e.target.disabled === true) {
// Add "preventSelection" to e.target.className// Alternatively, change the focus to somewhere else!
} else {
// Remove "preventSelection" from e.target.className
}
}
// Blah, blah, blah-blah blah
textBox.addEventListener("select", preventDisabledControlTextCopy, false);
It is never a waste of time to seek options. I skipped many details, but I made the important part explicit (as Stackoverflow is a tool people use to learn things). Implementation is up to you.
Final Thoughts:
The best answer might be to use CSS and JavaScript and toggle visibility: hidden
(IE 4+) or display: none
(IE 8+), depending on your scenario, DOM structure, and the complexity you are able to manage.
Dynamic forms are a great way to experience the interplay between HTML, CSS, and JavaScript.
Post a Comment for "Cross-browser: Different Behaviors For Disabled Input Fields (the Text Can/can't Be Copied)"