动态更改html5输入控件所需的分支 [英] dynamically change required atributte for html5 input control

查看:126
本文介绍了动态更改html5输入控件所需的分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入控件,它是必填字段。但是,我想使用javascript动态更改所需的属性,以便它可以变得不需要。但是,它不起作用。任何想法如何使它工作?

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?

window.onload = function(){
    document.getElementById("website").setAttribute("required","false");
}

<input id="website" type="url" required>


推荐答案

必填是所谓的 布尔属性。这仅仅表明输入是必需的。它没有什么价值。

required is a so called boolean attribute. It's mere existence on the element indicates that the input is required. It doesn't matter which value it has.

删除该属性,如果您想使输入可选(对所有布尔属性也一样):

Remove the attribute if you want to make the input optional (same goes for all boolean attributes):

document.getElementById("website").removeAttribute("required");

或者,访问 DOM属性并将其设置为 false :

Alternatively, access the DOM property and set it to false:

document.getElementById("website").required = false;

您通常应该倾向于处理属性而不是属性。它也使意图更清晰。

You should usually prefer dealing with properties than with attributes. It also makes the intentions clearer.

这篇关于动态更改html5输入控件所需的分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆