[javascript] jQuery add required to input fields

I have been searching ways to have jQuery automatically write required using html5 validation to my all of my input fields but I am having trouble telling it where to write it.

I want to take this

 <input type="text" name="first_name" value="" id="freeform_first_name"

and have it automatically add required before the closing tag

 <input type="text" name="first_name" value="" id="freeform_first_name"
 maxlength="150" required>

I thought I could do someting along the lines of

$("input").attr("required", "true");

But it doesn't work. Any help is greatly appreciated.

This question is related to javascript jquery validation

The answer is



You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:

$("input").attr("required", true);

I have found that the following implementations are effective:


$('#freeform_first_name').attr('required', 'required');

These commands (attr, removeAttr, prop) behave differently depending on the version of JQuery you are using. Please reference the documentation here: https://api.jquery.com/attr/

Using .attr method

.attr(attribute,value); // syntax

.attr("required", true);
// required="required"

.attr("required", false);

Using .prop

.prop(property,value) // syntax

.prop("required", true);
// required=""

.prop("required", false);

Read more from here


Should not enclose true with double quote " " it should be like

$(document).ready(function() {            
   $('input').attr('required', true);   

Also you can use prop

jQuery(document).ready(function() {            
   $('input').prop('required', true);   

Instead of true you can try required. Such as

$('input').prop('required', 'required');

I found that jquery 1.11.1 does not do this reliably.

I used $('#estimate').attr('required', true) and $('#estimate').removeAttr('required').

Removing required was not reliable. It would sometimes leave the required attribute without value. Since required is a boolean attibute, its mere presence, without value, is seen by the browser as true.

This bug was intermittent, and I got tired of messing with it. Switched to document.getElementById("estimate").required = true and document.getElementById("estimate").required = false.

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with jquery tag:

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) Only on Firefox "Loading failed for the <script> with source" How to prevent page from reloading after form submit - JQuery Vue component event after render How to use jQuery Plugin with Angular 4? How to disable a ts rule for a specific line? Bootstrap 4 File Input How to force reloading a page when using browser back button? Datatables Select All Checkbox Unable to preventDefault inside passive event listener Getting Error "Form submission canceled because the form is not connected" How to create multiple page app using react Set height of chart in Chart.js console.log(result) returns [object Object]. How do I get result.name? Setting and getting localStorage with jQuery JQuery: if div is visible Using OR operator in a jquery if statement Deprecation warning in Moment.js - Not in a recognized ISO format How to use aria-expanded="true" to change a css property DataTables: Cannot read property style of undefined Disable Chrome strict MIME type checking Consider marking event handler as 'passive' to make the page more responsive Cannot open local file - Chrome: Not allowed to load local resource "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project what is right way to do API call in react js? why $(window).load() is not working in jQuery? How to use JQuery with ReactJS $(...).datepicker is not a function - JQuery - Bootstrap remove first element from array and return the array minus the first element How to use a jQuery plugin inside Vue Uncaught SyntaxError: Invalid or unexpected token jquery 3.0 url.indexOf error How to redirect page after click on Ok button on sweet alert? Content Security Policy: The page's settings blocked the loading of a resource Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document' Checkbox value true/false vue.js 'document.getElementById' shorthand Removing legend on charts with chart.js v2

Questions with validation tag:

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery How do I turn off the mysql password validation? How to add form validation pattern in Angular 2? Laravel password validation rule Validating Phone Numbers Using Javascript How to validate an e-mail address in swift? javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory' Validate date in dd/mm/yyyy format using JQuery Validate How to properly validate input values with React.JS? Laravel: Validation unique on update How do I make an input field accept only letters in javaScript? Asking the user for input until they give a valid response HTML 5 input type="number" element for floating point numbers on Chrome Laravel update model with unique validation rule for attribute Regex for Mobile Number Validation How can I require at least one checkbox be checked before a form can be submitted? Comparing two input values in a form validation with AngularJS An invalid form control with name='' is not focusable Regex date validation for yyyy-mm-dd How do you do dynamic / dependent drop downs in Google Sheets? How to Call a JS function using OnClick event Javascript Date Validation ( DD/MM/YYYY) & Age Checking Excel data validation with suggestions/autocomplete HTML5 form validation pattern alphanumeric with spaces? HTML5 phone number validation with pattern Implement Validation for WPF TextBoxes How to check if bootstrap modal is open, so I can use jquery validate? jQuery add required to input fields Show red border for all invalid fields after submitting form angularjs Check if input value is empty and display an alert show validation error messages on submit in angularjs How to set HTML5 required attribute in Javascript? Validate phone number using javascript Form Validation With Bootstrap (jQuery) How to check if user input is not an int value How to check if that data already exist in the database during update (Mongoose And Express) Email address validation using ASP.NET MVC data type attributes HTML5 validation when the input type is not "submit" Angularjs prevent form submission when input validation fails HTML/JavaScript: Simple form validation on submit Java Regex to Validate Full Name allow only Spaces and Letters