Does display: none disable an <input>?

2019-08-12 17:27发布

问题:

I've experienced before the phenomenon that if an <input> tag has the CSS property display: none, then its value isn't submitted with its parent form. I'm now in the curious situation where that behaviour is helpful!

Can I rely on display: none to prevent inclusion of an input when its form is submitted, or is it technically a deviation from the spec?

Edit: The answers so far have all focussed on other ways of doing this, and the necessity of back-end validation, so let me be clear; I know this is a slightly odd way of doing things, and I know I need to validate on the back end. I already am; it's just that the format of the parameter I'm getting back makes one particular aspect of my processing slightly tricky.

As an attempt to rephrase the question slightly more clearly: Is there a reliable in-CSS way to prevent an input from being included with its form? It appears that setting a field's display to none works, but I haven't been able to tell whether it should work. I don't care about users potentially editing the front end HTML / CSS, because I will catch that on the back-end. You may assume a non-malicious user.

回答1:

No. You should definitely use the disabled attribute.

With HTML5, some browsers(i.e. Chrome) will even prevent you from submitting the form when a required field was set to display:none



回答2:

If the radio buttons represent two sets of complex values, it sounds like you are doing it right by storing that information as the radio button's value attribute.

That said, since you are already having the user pick a radio button which determines which hidden inputs are applicable, why can't you handle that in the validation code? You could check the value of the radio button first, and then take one action or another.

This would make it more difficult for someone to work their way around your code because the form wouldn't change based on user interaction, only the items processed would. Someone couldn't make a enable a disabled hidden form element because there wouldn't be one, the ones that don't apply would just be ignored.



回答3:

You can not rely on it as users can add values to that input, but if it's just to carry on some info, like to a second form and so on, just make sure to validate it in the backend always! You may wanna consider using php sessions :)



标签: html css forms