We can use jQuery to add a required attribute to an input field by using the jQuery attr() method to target the required attribute on an input element.


Let’s see an example of this.

Let’s say we have the following HTML:

If we want to make it so that the user has to input their name to be able to submit the form, we can add a required attribute to that input field using jQuery.


If you are using WordPress, don’t forget to change the $ to jQuery as below:


Note that we can also achieve the same result using the jQuery prop() method.


An Interactive Example of Using jQuery to Add a Required Attribute to an Input Field

Below we will have a simple form with a name field and a submit button. One thing that is common in a lot of online forms is making sure actual information is entered before allowing the user to submit a form.

So below we will have a form where the user will have the option to add a required attribute to the name field so that you can only submit the information if you put in anything in the name field.

Here is the HTML code:

Make the name field above required

To make the name field be required to submit the form, we simply will use our code from above. We will use the attr() method to set the required property of the name input field to true.

Once we add the required field, we will simply hide the button to add the required option using the jQuery hide() method.

Here is the code:


The final code and output for this example is below.

Make sure to send the form without requiring a name attribute at first to see what happens.

Code Output:

Make the name field above required

Full Code:

Make the name field above required

Hopefully this article has been useful to help you understand how to use the jQuery to add a required attribute.

Categorized in:


Last Update: March 11, 2024