jQuery 为所有表单元素添加只读属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4027236/
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-26 16:31:39  来源:igfitidea点击:

Adding readonly attribute to all form elements

jqueryhtmlforms

提问by Phill Pafford

I'm using jQuery to add a readonly attribute to all form elements but can't seem to figure out how to do this.

我正在使用 jQuery 向所有表单元素添加只读属性,但似乎无法弄清楚如何执行此操作。

Here is what I'm trying:

这是我正在尝试的:

$('#form1').each( function() { $(this).attr('readonly', true); });

I have a simple form using label/input to display form elements. Also I'm using tipsy(Tool tip plug-in) as well as Formalize(Look and Feel Plug-in)

我有一个使用标签/输入来显示表单元素的简单表单。此外,我正在使用Tipsy(工具提示插件)以及Formalize(外观和感觉插件)

回答by Kobi

Try this:

尝试这个:

$('#form1 input').attr('readonly', 'readonly');
  • You may want to include more elements #form1 input, #form1 textarea, #form1 select
  • In jQuery, you usually don't need to iterate over the collection. attrwould work for a collection same as for a single element.
  • In your case, #form1matched just the <form>element, and eachwas triggered once, for that element. To find allelements (input or not), you can write #form1 *.
  • 您可能想要包含更多元素 #form1 input, #form1 textarea, #form1 select
  • 在 jQuery 中,您通常不需要遍历集合。attr将适用于与单个元素相同的集合。
  • 在您的情况下,#form1仅匹配该<form>元素,并为该元素each触发一次。要查找所有元素(输入与否),您可以编写#form1 *.

回答by John Hartsock

This is even better use the input selector. Also note Read only is only for input type of text and password and textarea . It will not work on select elements, radio, checkboxes, buttons. If you want to display but not allow them to type or click. Try using disabled.

这甚至更好地使用输入选择器。另请注意 Read only 仅适用于 text 和 password 以及 textarea 的输入类型。它不适用于选择元素、单选、复选框、按钮。如果要显示但不允许他们键入或单击。尝试使用禁用。

$("#form1 :input").attr("disabled", true);

Note: by using disabled it will grey out the input, select or textarea but will not post this element when submitted. If you need it to post let me know and I can help you out.

注意:使用 disabled 会使 input、select 或 textarea 变灰,但在提交时不会发布此元素。如果您需要它,请告诉我,我可以帮助您。

Here is a demohttp://jsfiddle.net/j5PAn/

这是一个演示http://jsfiddle.net/j5PAn/

回答by Emmanuel

To get all elements of form:

要获取表单的所有元素:

$.each($('form').serializeArray(), function(index, value){
    $('[name="' + value.name + '"]').attr('readonly', 'readonly');
});

回答by Rossitten

<form>
    <fieldset disabled>
        <input type="text">
        <input type="radio">
        <input type="checkbox">
    </fieldset>
</form>

probably the best way to do that

可能是最好的方法