I am wondering if it's possible to set an element "required" based on some other element state. For instance, say I have an input element that I want to be "required" if and only if the user checks a specific checkbox. First, is this possible to do it without the use of JavaScript? Second, if we use JavaScript, of course one could set up a rule / validation if the user checks that checkbox, but what about consistency regarding the default browser validation errors? Would it be "correct" to add the "required" attribute to the element once the checkbox is clicked? I don't see an alternative here. What are your thoughts on this one?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I don't think you can do this without javascript.
With javascript, you could do this easily enough.
I would add the required
attribute only after the checkbox is clicked.
In fact, I would make this a toggled
piece, so that the user can uncheck and unrequire the input.
However, I would not rely on browser's implementation of the required
attribute. Instead, I would create my own required notification using some CSS (highlighting, animation, displaying some words).
回答2:
You may use polyfills to emulate native validation when not available:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills