Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Jquery validation plugin work on inputs with no name attribute

Well it took me long enough to find out that the JQuery form validation plugin only works on fields with a "name" attribute.

Anyway, I use it to make all the fields required.

My problem is that at some point, I have one text input

<div id='choices'>
  <input type='text' />
</div>
<a href='#' id='add-choice' >Add input </a>

the user can add as many text inputs as he wants :

$("#add-choice").live("click",function(){
                    $("#choices").append("<input type='text' /><br>");
});

And I want these new fields to be also required. Even if I give a name to the first input. What should I do for the new inputs added dynamically ?

Is there a way to use the plugin without using the name attr, or is there another solution ?

like image 433
lady_OC Avatar asked May 29 '13 12:05

lady_OC


3 Answers

What should I do for the new inputs added dynamically?

Give them a name, any name

Is there a way to use the plugin without using the name attr?

No

Is there another solution?

It depends on what you are doing with the fields - you clearly don't need a name on them for any other reason than to make jquery validate work, so why don't you just make up a name and call them all that?

correction - need unique names see comments

var i = 0;
$("#add-choice").live("click",function(){
 $("#choices").append("<input type='text' name='bob" + i + "' class='required'/><br>");
 i = i + 1;
});
like image 146
Dr Blowhard Avatar answered Sep 23 '22 04:09

Dr Blowhard


Quote OP:

"Is there a way to use the plugin without using the name attr"

No, you cannot use the jQuery Validate plugin if you do not have name attributes on all of your fields.

As per documentation:

Markup recommendations

The name attribute is '''required''' for input elements, the validation plugin doesn't work without it.

The "workaround" is to have jQuery create a unique name when it creates the new input.

like image 1
Sparky Avatar answered Sep 20 '22 04:09

Sparky


Yes you can do it, but with limitations

Limitation: You will not have flexibility to change messages while using different rules.

<form ="validationForm">
<input type="text" class="required" title="required message" />
</form>

jQuery("#validationForm").validate();
like image 2
kamal pal Avatar answered Sep 20 '22 04:09

kamal pal