Dynamically change required attribute to control html5 input

I have an input control that is required. However, I want to use javascript to dynamically change the required attribute so that it cannot be needed. However, this does not work. Any idea how to make it work?

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

<input id="website" type="url" required>
+4
source share
3 answers

requiredis the so-called boolean attribute . This simple existence on an element indicates the need for input. No matter how important it is.

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

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

DOM false:

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

, . .

+3

, removeAttribute()

+3

, "" . XHTML HTML-:

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

( 'hidden' , hidden = "hidden" )

In any case, when you try to change the value of a hidden attribute in JavaScript, setting it to false does not work. However, setting it to an empty string means that you can try "required":

 document.getElementById("website").required="";
 document.getElementById("website").required="required"; //when required wanted
0
source

All Articles