text如果可能,我想禁用使用 JavaScript在类型输入字段中写入。输入字段是从数据库填充的;这就是为什么我不希望用户修改它的值。
如何禁用输入类型=文本?
IT技术
javascript
html
                    2021-03-10 02:28:05
                
                    
                
            
        6个回答
            document.getElementById('foo').disabled = true;
或者
document.getElementById('foo').readOnly = true;
请注意,readOnly应该在驼峰式大小写中才能在 Firefox 中正常工作(魔术)。
演示:https : //jsfiddle.net/L96svw3c/——在某种程度上解释了disabled和之间的区别readOnly。
如果数据是从数据库填充的,您可能会考虑不使用<input>标签来显示它。不过,您可以直接在标签中禁用它:
<input type='text' value='${magic.database.value}' disabled>
如果您稍后需要使用 Javascript 禁用它,您可以设置“禁用”属性:
document.getElementById('theInput').disabled = true;
我建议不要将值显示为 an 的原因<input>是,根据我的经验,它会导致布局问题。如果文本很长,那么<input>用户将需要尝试滚动文本,这不是正常人会猜到的。如果你只是将它放入 a<span>或其他东西,你会有更多的造型灵活性。
你也可以通过jquery:
$('#foo')[0].disabled = true;
工作示例:
$('#foo')[0].disabled = true;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="foo" placeholder="placeholder" value="value" />
获取您喜欢的输入框的引用(例如document.getElementById('mytextbox'))并将其readonly属性设置为true:
myInputBox.readonly = true;
或者,您可以简单地内联添加此属性(不需要 JavaScript):
<input type="text" value="from db" readonly="readonly" />