How to Add Required Attribute to Input Field in Jquery

January 14, 2022
Jquery
How to Add Required Attribute to Input Field in Jquery

In this post, you will learn how to add the required attribute to the input field in jquery.

When we are creating a form, we need to make some of the fields required, and in some cases, we have to add the required attribute dynamically to the input field in jquery.

Let’s get started!

Step 1: Create HTML Boilerplate

First I am creating the HTML Boilerplate and including the jquery library.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</body>
</html>

Step 2: Create Form

I will create a form in the body tag, in which I have added an input field with class text-field and the submit button.

<form action="">
  <input type="text" class="text-field" placeholder="This field is required">
  <input type="submit" value="submit">
</form>

It will show something like this:

Now if press the submit button, the form will get submitted, whether the field is filled or not.

Now let’s add the required attribute to the field via jquery

Step 3: Add a required attribute to the input field using jquery

Now we will add the required attribute to the input field of class text-field . Include the following code right after jquery include in the scripttag.

$('.text-field').prop('required',true);

So now if we submit the form, it will not submit unless we under some text in the text-field.

Complete Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>

<form action="">
  <input type="text" class="text-field" placeholder="This field is required">
  <input type="submit" value="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
  $('.text-field').prop('required',true);
  </script>
</body>
</html>

Conclusion:

Hope you have learned today in the above article, how to add the required attribute in HTML using jquery.

Let me know if you have any questions in the comments. See you soon!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon