206
votes

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"
 maxlength="150">

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.

6
Is it not wrapped in dom ready? $(function(){....});PSL
if 'input' is an id the jquery is missing the # in the selector here.John Meyer
@JohnMeyer "input" is a tag selector. No # needed if targeting input tagsSpartacus

6 Answers

491
votes
$("input").prop('required',true);

DEMO FIDDLE

58
votes

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);
35
votes

I have found that the following implementations are effective:

$('#freeform_first_name').removeAttr('required');

$('#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/

10
votes

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

https://stackoverflow.com/a/5876747/5413283

6
votes

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.

6
votes

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');