jQuery add required to input fields

192

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.

This question is tagged with javascript jquery validation

~ Asked on 2013-10-03 18:38:18

The Best Answer is


461

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

DEMO FIDDLE

~ Answered on 2013-10-03 18:39:25


55

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

~ Answered on 2014-07-25 04:43:27


Most Viewed Questions: