最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - dynamically change required atributte for html5 input control - Stack Overflow

programmeradmin3浏览0评论

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 bee 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>

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 bee 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>
Share Improve this question edited May 10, 2016 at 22:04 Vini.g.fer 11.9k19 gold badges65 silver badges99 bronze badges asked Sep 2, 2014 at 16:34 nulloxnullox 3952 gold badges8 silver badges18 bronze badges 1
  • possible duplicate of Bypass HTML "required" attribute when submitting – AeroX Commented Sep 2, 2014 at 16:41
Add a ment  | 

3 Answers 3

Reset to default 6

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");

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.

You probably need to use the removeAttribute() method.

This problem is similar to another involving the "hidden" attribute. And for wider patibility, consider the XHTML form of using the attribute, instead of the HTML form:

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

(The similarity to 'hidden' is that the attribute is specified as 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':

 document.getElementById("website").required="";
 document.getElementById("website").required="required"; //when required wanted
发布评论

评论列表(0)

  1. 暂无评论