我如何添加只读到特定的<输入>?.attr('readonly')不起作用。


.attr('readonly', 'readonly')应该可以做到。你的.attr('readonly')只返回值,不设置值。


jQuery < 1.9

$('#inputId').attr('readonly', true);

jQuery 1 + 9。

$('#inputId').prop('readonly', true);

阅读更多关于prop和attr的区别


我认为“disabled”排除了POST上发送的输入


启用只读功能:

$("#descrip").attr("readonly","true");

禁用只读

$("#descrip").attr("readonly","");

你可以使用.removeAttr;

$('#descrip').removeAttr('readonly');

使用$ .prop ()

$("#descrip").prop("readonly",true);

$("#descrip").prop("readonly",false);

Readonly是html中定义的一个属性,所以把它当作一个属性来对待。

如果你想让对象不可编辑,你需要在对象中有类似readonly="readonly"的东西。 如果你想让它再次可编辑,你就不会有像readonly= "这样的东西(如果我理解正确的话,这不是标准的)。您确实需要整体删除该属性。

因此,在使用jquery时添加和删除它是有意义的。

设置为只读:

$("#someId").attr('readonly', 'readonly');

删除只读的:

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

这是唯一对我有效的选择。 希望能有所帮助!


使用setAttribute属性。注意,如果选择1,则在文本框上应用readonly属性,否则将删除readonly属性。

http://jsfiddle.net/baqxz7ym/2/

document.getElementById("box1").onchange = function(){
  if(document.getElementById("box1").value == 1) {
    document.getElementById("codigo").setAttribute("readonly", true);
  } else {
    document.getElementById("codigo").removeAttribute("readonly");
  }
};

<input type="text" name="codigo" id="codigo"/>

<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>

对于jQuery版本< 1.9:

$('#inputId').attr('disabled', true);

对于jQuery版本>= 1.9:

$('#inputId').prop('disabled', true);

检查下面的代码:

<input id="mail">

<script>

 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again

</script>