Javascript 将表单中的所有字段设为只读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4386732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:12:43  来源:igfitidea点击:

Making Readonly all fields in a form

javascripthtmlcss

提问by scunliffe

How can we make all fields in a form read only ?

我们如何使表单中的所有字段都只读?

回答by scunliffe

This should work:

这应该有效:

$(':input').attr('readonly','readonly');

Or if you have a specific form...

或者,如果您有特定的表格...

$('#myFormID :input').attr('readonly','readonly');

If you are using just plain JavaScript, you'll want to do this.

如果你只使用普通的 JavaScript,你会想要这样做。

var f = document.forms['myFormNAME'];
for(var i=0,fLen=f.length;i<fLen;i++){
  f.elements[i].readOnly = true;//As @oldergod noted, the "O" must be upper case
}

One side note... although you can "set" the readonly flag on checkboxand hiddeninput fields... it won't actually makethem readonly.

一个旁注......虽然你可以“设置”只读标志checkboxhidden输入字段......它实际上不会使它们成为只读。

回答by matuuar

A solution without javascript, enclose all fields in fieldsets and add disabledtag to fieldsets.

一个没有 javascript 的解决方案,将所有字段包含在字段集中并将disabled标签添加到字段集中。