Monday, December 30, 2013

Javascript validation for dynamic element



Many time in web-application we come across the functionality to build - adding dynamic form elements and validating them. its pretty simple with .rules() and validate()


 var newElement = $('<input type="text" name="input' + count + '" value="" />');
            $('form').append(newElement);
            newElement.rules('add', {
                required: true,
                messages: {
                    required: 'This field is required'
                }
            });

and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
            numberIncr++;
        }

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // prevent default submit action         
            event.preventDefault();

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("validates");
            } else {
                console.log("does not validate");
            }
        })

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator
        $('form.commentForm').validate();

   });


</script>



Know more about JAVASCRIPT, JQUERY, Form Validation, Validate
Hope you have enjoyed the post let us know your views.


1 comment:

  1. I have many times to search the blog for getting this programming segment to make the validation.But this blog only have the exact javascript validation coding.Its really great job.
    Web Development Company | Web Development Companies

    ReplyDelete

Any Questions or Suggestions ?

About

Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner