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

问题描述 投票:34回答:7

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

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

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

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

确保您将来使用<body onload="onLoadBody();">

javascript input readonly
7个回答
56
投票

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

document.getElementById('InputFieldID').readOnly = true;

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

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

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

<body onload="onLoadBody">

查看演示:jsfiddle


18
投票

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

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

并且在页面加载时运行,值得参考here


4
投票
document.getElementById("").readOnly = true

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


document.getElementById('TextBoxID').readOnly = false;   //to  disable readonly

2
投票

试试这个 :

document.getElementById(<element_ID>).readOnly=true;

-1
投票

I think you just have readonly="readonly"

<html><body><form><input type="password" placeholder="password" valid="123" readonly=" readonly"></input>


-2
投票

这里有一些示例如何设置readonly属性:

<form action="demo_form.asp">
  Country: <input type="text" name="country" value="Norway" readonly><br>
  <input type="submit" value="Submit">
</form>
© www.soinside.com 2019 - 2024. All rights reserved.