jquery validation dynamic fields

Solutions on MaxInterview for jquery validation dynamic fields by the best coders in the world

showing results for - "jquery validation dynamic fields"
Mathilda
24 Oct 2016
1You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
2
3And here is my solution that I've tested and it works:
4
5<script type="text/javascript">
6   $(document).ready(function() {
7        var numberIncr = 1; // used to increment the name for the inputs
8
9        function addInput() {
10            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
11            numberIncr++;
12        }
13
14        $('form.commentForm').on('submit', function(event) {
15
16            // adding rules for inputs with class 'comment'
17            $('input.comment').each(function() {
18                $(this).rules("add", 
19                    {
20                        required: true
21                    })
22            });            
23
24            // prevent default submit action         
25            event.preventDefault();
26
27            // test if form is valid 
28            if($('form.commentForm').validate().form()) {
29                console.log("validates");
30            } else {
31                console.log("does not validate");
32            }
33        })
34
35        // set handler for addInput button click
36        $("#addInput").on('click', addInput);
37
38        // initialize the validator
39        $('form.commentForm').validate();
40
41   });
42
43
44</script>
45And the html form part:
46
47<form class="commentForm" method="get" action="">
48    <div>
49
50        <p id="inputs">    
51            <input class="comment" name="name0" />
52        </p>
53
54    <input class="submit" type="submit" value="Submit" />
55    <input type="button" value="add" id="addInput" />
56
57    </div>
58</form>
59Good luck! Please approve answer if it suits you!