In this blog post, we learn how to add and remove a required attribute in jquery. By this method, You not only able to remove or add the “required” attribute, But you can remove or add another attribute also.
We do the task using attr() method. The attr() method sets or returns attributes and values of the selected elements
So let’s start
Remove Required Attribute
HTML
<form>
<div class="mb-3">
<label for="inputName" class="form-label">Enter Name</label>
<input type="text" class="form-control" id="inputName" required >
</div>
<a href="javascript:;" id="submit" class="btn btn-sm btn-info"> Remove Attribute </a>
<hr>
<p><span id="msg"></span></p>
</form>
Jquery
<script>
$(document).ready(function(){
$("#submit").click(function(){
$('#inputName').attr('required', false);
document.getElementById("msg").innerHTML = "Required attribute removed from name input";
});
});
</script>
Result

When you click on the button “remove attribute” jquery will remove the Required attribute from the name input box.
Add Required Attribute
In this section, we can easily add the required attributes to the input box. here is the example.
<form>
<div class="mb-3">
<label for="inputName" class="form-label">Enter Name</label>
<input type="text" class="form-control" id="inputName" >
</div>
<a href="javascript:;" id="submit" class="btn btn-sm btn-info"> Add Attribute </a>
<hr>
<p><span id="msg"></span></p>
</form>
Javascript
<script>
$(document).ready(function(){
$("#submit").click(function(){
$('#inputName').attr('required', true);
document.getElementById("msg").innerHTML = "Required attribute added in name input";
});
});
</script>
Result

So here we complated post on How to Add and Remove Required in Jquery.
I hope this post will be helpful for you.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.