Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTML Input Area Readonly but Selectable

I've got an input area that's transparent and when you click on it the glowing border shows up (intended) and you can edit the text. I'm trying to get the glowing border to still show up when you click it but make the text inside uneditable.

<input style='border:none; background:none;' value='TEXT'>  

Adding readonly or readonly="readonly" makes the input act like an uneditable div, you can't double click the input area to select it all and the glowing border doesn't show up. How can I retain the input functionality without allowing the text to be changed?

like image 649
Crizly Avatar asked Jul 01 '16 15:07

Crizly


Video Answer


2 Answers

You can use the readonly attribute with some CSS:

input:focus {
    box-shadow: 0 0 2px 2px #3d94db;
}
<input style='border:none; background:none;' value='TEXT' readonly> 
like image 125
j08691 Avatar answered Oct 07 '22 14:10

j08691


Maybe give a default value to an input field

The default protocol when a user presses a key is to type in text. We can override that with preventDefault().

Now, I just realized that you can circumvent this by using the mouse right click event. So another event listener is required contextmenu. Now, you can no longer cheat with this.

var inputField = document.getElementById("input-field");

inputField.addEventListener("keydown", function(event) {
    event.preventDefault();
});

inputField.addEventListener("contextmenu", function(event) {
    event.preventDefault();
});
<input type="text" id="input-field" value="This value can be selected" />
like image 26
Richard Hamilton Avatar answered Oct 07 '22 15:10

Richard Hamilton