alphanumeric alphanumeric - 10 months ago 47
HTML Question

How to set Element as ReadOnly by clicking outside the element

I have an

element set to
by default:

<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(">

If the user double-clicks this element it will be set to editable with:

function onDoubleClick(id){
var element = $('#'+id);
if (element.prop('readonly')==true) { element.prop('readonly', false);}
else { element.prop('readonly', true); }

Apparently this
element will stay editable up until the user double clicks it again. I wonder if I could link a mouse
that happens outside of the
element to turn it into readonly again. How to achieve it?

Answer Source

you could rely on the blur event to take action when it loses focus

function onDoubleClick(elem) {
  console.log('toggling readonly property');
  var element = $(elem);
  element.prop('readonly', !element.prop('readonly')); // toggle

function lostFocus(elem) {
  var element = $(elem);
  element.prop('readonly', true);
input {
  background-color: white;
input[readonly] {
  background-color: #ccc;
<script src=""></script>

<input readonly id="uniqueId" type="text"  ondblclick="onDoubleClick(this)" onblur="lostFocus(this)">