如何使用JavaScript只读输入字段?

chr*_*ris 40 javascript input readonly

我知道你可以添加readonly="readonly"到输入字段,因此它不可编辑.但我需要使用javascript来定位输入的id并使其只读,因为我无法访问表单代码(它是通过营销软件生成的)

我不想禁用输入,因为应该在提交时收集数据.

这是我在以下建议中添加的页面,目前还没有运气:

https://www.pages05.net/engagedigital/inputReadOnly/test?spMailingID=6608614&spUserID=MTI5MDk4NjkzMTMS1&spJobID=Nzk4MTY3MDMS1&spReportId=Nzk4MTY3MDMS1

确保您<body onload="onLoadBody();">将来使用此功能的任何人都可以使用.

Vij*_*jay 62

您可以获取input元素,然后将其readOnly属性设置true为如下所示:

document.getElementById('InputFieldID').readOnly = true;
Run Code Online (Sandbox Code Playgroud)

具体来说,这就是你想要的:

<script type="text/javascript">
  function onLoadBody() {
    document.getElementById('control_EMAIL').readOnly = true;
  } 
</script>
Run Code Online (Sandbox Code Playgroud)

onLoadBody()在body标签上调用此函数,如:

<body onload="onLoadBody">
Run Code Online (Sandbox Code Playgroud)

查看演示:jsfiddle.

  • 请注意区别,在 HTML 中,属性是“readonly”(全部小写),而在 Javascript 中,属性是“readOnly”(大写 O)。感谢你的回答。 (3认同)
  • 太棒了 - 谢谢 Vijay,我只需要让 body 引用具有 &lt;body onload="onLoadBody();"&gt; - 以防将来有人看到这个。 (2认同)

Cha*_*ley 21

以上答案对我不起作用.以下是: document.getElementById("input_field_id").setAttribute("readonly", true);

并删除readonly属性: document.getElementById("input_field_id").removeAttribute("readonly");

并且在页面加载时运行,这里值得参考.


gez*_*uzz 5

document.getElementById("").readOnly = true
Run Code Online (Sandbox Code Playgroud)


Mum*_* VP 5

document.getElementById('TextBoxID').readOnly = true;    //to enable readonly


document.getElementById('TextBoxID').readOnly = false;   //to  disable readonly
Run Code Online (Sandbox Code Playgroud)