jQuery add required to input fields

2022-08-30 00:45:36

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.


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

DEMO FIDDLE


答案 2

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