alphanumeric alphanumeric - 2 days ago 5
HTML Question

How to set Element as ReadOnly by clicking outside the element

I have an

<input>
element set to
readonly
by default:

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


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
<input>
element will stay editable up until the user double clicks it again. I wonder if I could link a mouse
click
that happens outside of the
<input>
element to turn it into readonly again. How to achieve it?

Answer

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) {
  console.log('lostFocust');
  var element = $(elem);
  element.prop('readonly', true);
}
input {
  background-color: white;
}
input[readonly] {
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

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

Comments