Bram W.
Bram W.

Reputation: 1607

Disable text selection in textarea

I need to find a way to prevent users from selecting text in a textarea. The goal is to create a custom keyboard that is used to enter text in the textarea. I want users to be able to click on the textarea to set the caret position (which is already working right now). However, I don't want the users to be able to select certain parts of the inserted text, or there should at least be no visual indication of this. I have already tried a few things, such as the following CSS, but without success.

textarea {
    -moz-user-select: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    user-select: none;
}

The solution can be in CSS and/or JavaScript, and it only has to work in Google Chrome.


Disabling the textarea will not work for me. As I mentioned, I want users to be able to place the caret at certain positions by clicking on the location. If I would disable the textarea, this functionality would be lost.

Upvotes: 10

Views: 21299

Answers (8)

Samuel Gfeller
Samuel Gfeller

Reputation: 1000

The answers didn't work for me, so I put a div with position: absolute; on top of the textarea, and it works perfectly.

Upvotes: 0

Calculamatrise
Calculamatrise

Reputation: 419

None of these solutions worked for me. Here's one of my own:

textarea::selection {
    background-color: transparent;
}

Upvotes: 1

Vinutha N
Vinutha N

Reputation: 166

Below code can help you

JS Code:

$(document).ready(function(){
   $('#txtInput').bind("cut copy paste",function(e) {
      e.preventDefault();
   });
});

Upvotes: 1

silvadori
silvadori

Reputation: 49

Or you can just put disabled="disabled" in textarea, like this :

<textarea disabled="disabled"></textarea>

Upvotes: 0

Martin Zeitler
Martin Zeitler

Reputation: 76639

A combination of the "readonly" property and "user-select" property works.

The 2nd rule disables the highlighted border on select, which is a kind of visual selection.

The "unselectable" property seems to be Opera/IE specific.

the styles:

.noselect {
   cursor: default;
   -webkit-user-select: none;
   -webkit-touch-callout: none;
   -khtml-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   -o-user-select: none;
}

.noselect:focus {
   outline: none;
}

the markup:

<textarea class="noselect" readonly="readonly" unselectable="on"></textarea>

read-only might be more suitable than disabled (one can still toggle with JS, upon click event).

Upvotes: 9

Ankur Dhanuka
Ankur Dhanuka

Reputation: 1237

<textarea disabled="readonly"></textarea>

tested it is working.

Upvotes: -3

Mike H.
Mike H.

Reputation: 1751

You can disable it with javascript:

document.getElementById("textarea").disable='true';

Upvotes: -2

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

<textarea unselectable="on" id="my_textarea"></textarea>

    *.unselectable {
   -webkit-user-select: none;
    }  

Upvotes: 4

Related Questions