Html 如何避免将 display:none 隐藏的输入字段发送到服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1374147/
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
How to avoid sending input fields which are hidden by display:none to a server?
提问by glaz666
Imagine you have a form where you switch visibility of several fields. And if the field is not displayed you don't want its value to be in request.
想象一下,您有一个表单,您可以在其中切换多个字段的可见性。如果该字段未显示,您不希望它的值出现在请求中。
How do you handle this situation?
你如何处理这种情况?
回答by karim79
Setting a form element to disabled will stop it going to the server, e.g.:
将表单元素设置为禁用将阻止它进入服务器,例如:
<input disabled="disabled" type="text" name="test"/>
In javascript it would mean something like this:
在 javascript 中,它的意思是这样的:
var inputs = document.getElementsByTagName('input');
for(var i = 0;i < inputs.length; i++) {
if(inputs[i].style.display == 'none') {
inputs[i].disabled = true;
}
}
document.forms[0].submit();
In jQuery:
在 jQuery 中:
$('form > input:hidden').attr("disabled",true);
$('form').submit();
回答by Benedict Cohen
You could use javascript to set the disabled attribute. The 'submit' button click event is probably the best place to do this.
您可以使用 javascript 设置禁用属性。“提交”按钮单击事件可能是执行此操作的最佳位置。
However, I would advise against doing this at all. If possible you should filter your query on the server. This will be more reliable.
但是,我建议完全不要这样做。如果可能,您应该在服务器上过滤您的查询。这样会更可靠。
回答by macio.Jun
If you wanna disable all elements or certain elements within a hidden parent element, you can use
如果要禁用隐藏父元素中的所有元素或某些元素,可以使用
$("div").filter(":hidden").children("input[type='text']").attr("disabled", "disabled");
This example http://jsfiddle.net/gKsTS/disables all textboxes within a hidden div
此示例http://jsfiddle.net/gKsTS/禁用隐藏 div 中的所有文本框
回答by Antonio Max
What about:
关于什么:
$('#divID').children(":input").prop("disabled", true); // disable
and
和
$('#divID').children(":input").prop("disabled", false); // enable
To toggle all children inputs (selects, checkboxes, input, textareas, etc) inside a hidden div.
在隐藏的 div 中切换所有子输入(选择、复选框、输入、文本区域等)。
回答by jsalvata
One very simple (but not always the most convenient) solution is to remove the "name" attribute -- the standard requires that browsers not send unnamed values, and all browsers I know abide to this rule.
一个非常简单(但并不总是最方便)的解决方案是删除“name”属性——标准要求浏览器不要发送未命名的值,我知道的所有浏览器都遵守这个规则。
回答by JMP
I would either remove the value from the input or detach the input object from the DOM so it doesn't exist to be posted in the first place.
我要么从输入中删除该值,要么将输入对象从 DOM 中分离出来,这样它就不会首先被发布。