Introduction
This Tip/Trick is a quick reference on how to remove the required from an input tag using simply JavaScript to achieve it.
Description
>Sometimes we have a very simple screen and we wouldn't want to import a library just for this one functionality. If you are using JQuery or anything else, by all means, use the functions provided. If not, I hope the following code becomes useful.
The Code
Lets get to it. If at a given web page you have a simple form that asks for the name and the phone as below:
<form method="post" style="border:1px solid black; padding:10px;">
<label>Name:</label><input type="text" id="name"></input><br/>
<label>Phone:</label><input type="text" id="requiredInput" required></input>
<br/>
<p>If you try to submit before disabling, the required message will pop up</p>
<input type="submit"></input>
</form>
But I have a friend (or a boss) who ask (or demmands) he only has to put his name and not his phone.
That is an easy and simple way to do it. At the input button, you can add a onClick() event if the following condition:
if( document.getElementById("name").value === "Jack"){
}
For this example, the simple comparison between the value in the name input box wiith the string "Jack" should be enough. (Let's assume he the only Jack there is :P)
For those used to JQuery, the way to go if you want to remove the required is
$("aTag").removeAttr("anAttribute");
But, as said before we are trying to accomplish it without the need for such.
In that case you could:
if( document.getElementById("name").value === "Jack"){
var theInput = document.getElementById("requiredInput");
theInput.removeAttribute("required");
}
Also, if the intention is to simply remove it, no checking required. you can do as follows:
if( document.getElementById("name").value === "Jack"){
document.getElementById("requiredInput").removeAttribute("required");
}
Notes
I've added a file to be downloaded. Hopefully it will help to further clarify and to work as an example.
The required attribute can be a bit buggy sometimes. If you are using chrome, make sure you write, click away from or do anything that will make it go away before closing the tab. Otherwise it may be carried around to the other screens.
After the post, the required will return to the input. Most probably know that, so its just a heads up.