javascript 动态更改 html5 输入控件所需的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25628209/
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
dynamically change required atributte for html5 input control
提问by nullox
I have an input control which is a required field. However, I want to use javascript to dynamically change the required attribute so it can become NOT required. However, it doesn't work. Any idea how to make it work?
我有一个输入控件,它是必填字段。但是,我想使用 javascript 来动态更改所需的属性,因此它可以变为不需要。但是,它不起作用。知道如何使它工作吗?
window.onload = function(){
document.getElementById("website").setAttribute("required","false");
}
<input id="website" type="url" required>
采纳答案by Felix Kling
required
is a so called booleanattribute. It's mere existence on the element indicates that the input is required. It doesn't matter which value it has.
required
是所谓的布尔属性。元素上的存在表明需要输入。它具有哪个值并不重要。
Removethe attribute if you want to make the input optional (same goes for all boolean attributes):
如果您想让输入成为可选,请移除该属性(所有布尔属性也是如此):
document.getElementById("website").removeAttribute("required");
Alternatively, access the DOM propertyand set it to false
:
或者,访问DOM 属性并将其设置为false
:
document.getElementById("website").required = false;
You should usually prefer dealing with properties than with attributes. It also makes the intentions clearer.
您通常应该更喜欢处理属性而不是属性。这也使意图更加清晰。
回答by netdog
You probably need to use the removeAttribute()
method.
您可能需要使用该removeAttribute()
方法。
回答by vernonner3voltazim
This problem is similar to another involving the "hidden" attribute. And for wider compatibility, consider the XHTML form of using the attribute, instead of the HTML form:
这个问题类似于另一个涉及“隐藏”属性的问题。为了更广泛的兼容性,请考虑使用属性的 XHTML 形式,而不是 HTML 形式:
<input id="website" type="url" required="required" />
(The similarity to 'hidden' is that the attribute is specified as hidden="hidden")
(与 'hidden' 的相似之处在于该属性被指定为 hidden="hidden")
Anyway, when trying to change the value of the hidden attribute in JavaScript, setting it to "false" doesn't work. However, setting it to an empty string does, so that is what you might try for 'required':
无论如何,当尝试在 JavaScript 中更改隐藏属性的值时,将其设置为“false”是行不通的。但是,将其设置为空字符串确实如此,因此您可以尝试使用“必需”:
document.getElementById("website").required="";
document.getElementById("website").required="required"; //when required wanted