Make text box editable using JavaScript

 ̄綄美尐妖づ 提交于 2019-12-20 04:15:42

问题


I've a textbox with readonly="readonly" that means I can not edit it. But what I want is to make this textbox editable when user double clicks on it.

What I've tried yet is:

<input size="10" readonly="readonly" ondblclick="setEditable(this)"/>

and in JavaScript:

 function setEditable(i){
     i.readonly = false;
 }

But this does not worked. So how can I make a textbox editable, which is readonly, when user double clicks on it?


回答1:


Update:

To make it readonly again:

var el = document.getElementById('txt');
el.onblur = function(){
  this.setAttribute('readonly');
};

You can do this:

<input size="10" readonly="readonly" id="txt" />

JS:

var el = document.getElementById('txt');
el.ondblclick = function(){
  this.removeAttribute('readonly');
};



回答2:


as above pure javascript example by sarfraz try to make your javascript unobtrusive much better practice

Also as a lot of people do if you have jquery on page now you can use that to do same

In jquery

$('#txt').removeAttr("readonly");




回答3:


To make text field editable

document.getElementById("TextFieldId").readOnly=true;

To make text field Uneditable

document.getElementById("TextFieldId").readOnly=false;


来源:https://stackoverflow.com/questions/5016326/make-text-box-editable-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!