js控制input只读操作,jQuery控制input只读操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hai7425/article/details/83543764

1、js为<input>设置readOnly属性

      <textarea name="content" id="content" cols="27" rows="6"></textarea>

      var cObj = document.getElementById("content");

      cObj.setAttribute("readOnly",'true');

2、js移除<input>readOnly属性

     var cObj = document.getElementById("content");

     cObj.removeAttribute("readOnly");

注意:一定要注意readOnly大小写!!!

----------------------------------------------------------------------------

input 框的只读属性:  readonly
在页面中直接添加为只读时,可在input中直接添加   readonly="readonly",但是如果想通过点击按钮来改变的话,需要通过js(或jquery)来实现。
最近一次使用这个,终于发现了以前写这个js控制的时候为什么总是那么郁闷了,原来,js  在对于readonly、disabled等属性设置时,有一个小bug(至少我是这么认为):首先,document.getElementById("id").readonly = "true";  设置input为只读,但是,当通过document.getElementById("id").readonly="false"  来去掉只读属性时,没有作用,此时,需要把  false  外面的引号给去掉js语句才能正常工作。
附:
1. jquery  通过id属性设置与取消只读属性


设置只读:$("#id").attr("readOnly","true");

取消只读:$("#id").attr("readOnly",false);

2.
 jquery  批量设置与取消只读属性
/*   id为sa的div中,所有input框
   */

设置只读:$("#sa input").attr("readOnly","true");
取消只读:$("#sa input").attr("readOnly",false);
---------------------
 

猜你喜欢

转载自blog.csdn.net/hai7425/article/details/83543764