alphanumeric alphanumeric - 5 days ago 5
HTML Question

How to turn INPUT element to readonly with Enter or Escape key

I have an

<input>
element set to readonly by default:

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


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

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


This
<input>
element will stay editable up until the user double-clicks it again. I wonder if there is a way to link an
Enter
key and the
Escape
key so the user could end the input by hitting one of those keyboard keys turning the
<input>
element back to readonly again. How to achieve it?

Answer

How about this working solution that works with the ENTER key. Hope it helps!

Updated Solution

$('input[type=text]').keypress(function(event){

	var keycode = (event.keyCode ? event.keyCode : event.which);
	if(keycode == '13'){
        if ($(this).prop('readonly')=== false) {
        $(this).prop('readonly', true); 
        }
        else { 
        $(this).prop('readonly', false); 
        }
    }
});
        
function onDoubleClick(elem){
    var element = $(elem);
    
    if (element.prop('readonly')=== true) {
        element.prop('readonly', false);
        if(!element.val()){
          element.val(".").val("");
        } 
        else{
        element.val($.trim(element.val(element.val()+" ").val()));
        }
    }
    else { 
        element.prop('readonly', true); 
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(this)"/>