问题描述
我知道您可以将readonly="readonly"
添加到输入字段中,以便其不可编辑.但是我需要使用javascript来定位输入的ID,并将其设置为只读,因为我无权访问表单代码(它是通过营销软件生成的)
I know you can add readonly="readonly"
to an input field so its not editable. But I need to use javascript to target the id of the input and make it readonly as I do not have access to the form code (it's generated via marketing software)
我不想禁用输入,因为应该在提交时收集数据.
I don't want to disable the input as the data should be collected on submit.
这是我在以下建议中添加的页面,到目前为止没有运气:
Here is the page I have added in the below suggestion with no luck so far:
确保以后对使用此代码的任何人使用<body onload="onLoadBody();">
.
Make sure you use <body onload="onLoadBody();">
for anyone using this in the future.
推荐答案
您可以获取输入元素,然后将其readOnly
属性设置为true
,如下所示:
You can get the input element and then set its readOnly
property to true
as follows:
document.getElementById('InputFieldID').readOnly = true;
具体来说,这就是您想要的:
Specifically, this is what you want:
<script type="text/javascript">
function onLoadBody() {
document.getElementById('control_EMAIL').readOnly = true;
}
</script>
在body标签上调用此onLoadBody()
函数,例如:
Call this onLoadBody()
function on body tag like:
<body onload="onLoadBody">
观看演示: jsfiddle .
这篇关于如何使用JavaScript将输入字段设置为只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!