Miura-shi
Miura-shi

Reputation: 4519

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"
 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.

Upvotes: 258

Views: 657974

Answers (6)

Dexter
Dexter

Reputation: 9314

Using .attr method

.attr(attribute,value); // syntax

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

.attr("required", false);
// output:

Using .prop

.prop(property,value) // syntax

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

.prop("required", false);
// output: 

Read more from here

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

Upvotes: 22

Rokan Nashp
Rokan Nashp

Reputation: 351

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

Upvotes: 9

John Meyer
John Meyer

Reputation: 2356

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/

Upvotes: 47

Doris Gammenthaler
Doris Gammenthaler

Reputation: 624

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.

Upvotes: 6

Joz Naveen Joz
Joz Naveen Joz

Reputation: 847

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

Upvotes: 71

Kiran
Kiran

Reputation: 20313

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

DEMO FIDDLE

Upvotes: 561

Related Questions