提交 display: none 元素内的表单字段

我有一个长的形式,我已经分为6个步骤。加载表单时,将加载所有步骤,但只有第一步可见。其余的有 display:none的 CSS,所以它们是隐藏的。当一个步骤完成并用 Javascript 进行验证时,当前步骤被设置为 display:none,新步骤被设置为 display:block。在最后一步,用户提交表单。但是,正如预期的那样,只提交页面上 display:block元素中的字段。使用 display:none的元素中的所有已完成字段将被忽略。

有办法提交 display:none元素中的字段吗?

如果没有,是否有其他方法达到同样的效果?

118387 次浏览

Set them to visibility:hidden and position:absolute instead. The fields will not be sent to the server with display:none, but will be with visibility:hidden. By also toggling "position" to "absolute" you should get the same visual effect.

Update This does not appear to be an issue anymore in any current browser (as of Nov of 2015). Fields are submitted even if display is set to 'none'. Fields that are 'disabled', however, will continue to not be submitted.

The HTML4, section 17.13.2, says explicitly that even hidden controls using display:none may be valid for submission.

https://www.w3.org/TR/html401/interact/forms.html

So if the browser ignores display:none then it is not fully HTML-capable. I recommend switching for a real browser.

There are bugs in many older browsers where "display:none" removes an item in weird ways...like Webkit browsers pre-2012, where "display:none" on say a submit button, then pressing "return", would not submit the form field data to the server. There are also cases where "display:none" added to input fields of type "hidden" to hide them in old IE browsers fail to send that input data to the server.

The consensus should always be to NOT USE "display:none" to hide form field data or any field that is not normally displayed anyway, but which still needs to be seen by say a screen reader, submit form field data, or be read by search engines. I only use "display:none" when I truly want to remove something temporarily from the page but later enable it again.

Below is an alternative to "display:none" that just hides the item visually from the user and removes it completely from the page flow without hiding its content or data:

.hide {
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
visibility: hidden !important;
}

If you find that your input is not submitted with display: none; and you want your element to not occupy space there is another option which I do not see mentioned anywhere.

It seems to work, but only if your element has no children.

display: contents;

Check the browser support as it is a newish CSS feature.

display:none - doesn't mean that form elements are not submitted (just not displayed)... They are submitted in the current version of Chrome, despite being hidden.