0

Say I have this Jquery code:

$('.additems').click(function () {
            $table = $('.item');

   $table.append('<tr> <td> <input type="textbox" name="test"> </td>   </tr>');

});

And I want to enable the validation from the [Required] attribute of my model who contains the property test

I tried adding the autogenerated html from the @Html.ValidationMessageFor which is <span class="field-validation-valid" data-valmsg-for="test" data-valmsg-replace="true"></span> but it's not working.

How do I do it?

Carlos Miguel Colanta
  • 2,685
  • 3
  • 31
  • 49
  • 1
    In your view, temporarily create the elements using `@Html.TextBoxFor(m => m.test)` and `@Html.ValidationMessageFor(m => m.test)` and inspect the html it generates. And its `type="text"`, not `"textbox"`. And best guess is your trying to dynamically add new items to a collection, in which case refer the answers [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) –  Jul 09 '16 at 23:38
  • So get the generated html and append it with the same format/contents? – Carlos Miguel Colanta Jul 10 '16 at 00:06
  • 1
    Yes, If the property your bind to is `IEnumerable test` then it will work, but if your binding to a collection of complex obects, then you will need indexers as per the answers I linked to. –  Jul 10 '16 at 00:09
  • Oh I didnt put indexers for the sake of simplicity but that is what I am doing right now. Anyway I'll try what you suggested. Thank you. – Carlos Miguel Colanta Jul 10 '16 at 00:16

1 Answers1

0

You can try different solution

    $('.additems').click(function () {
    $table = $('.item'); 
    $table.append('<tr> <td> <input type="textbox" class="myReq" name="test"> </td>   </tr>');

});
function foo() {
    $(".myReq").each(function () {
        //Your Control
    });
}
Serdar KUŞ
  • 404
  • 1
  • 4
  • 16