Tuesday, October 29, 2013

Jquery Validate Dynamic Form

Scenario:

In a html page, there are button and a div (newFormDiv), when user click the button, it will call up an ajax function to write a new form (commentForm) in div newFormDiv. in the new form, user will input something in artPlaceName, the length must be bigger than 1.

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
   <script src="formajax.js"></script>
</head>
<body>
<div id="textarea">
This is a text area.
</div>
<div id="buttonarea">
<button>Create New Form</button>
</div>
<div id="newFormDiv">
This is new form area.
</div>
</body>
</html>

futureForm.php


<?php
echo '
  <form id="commentForm" method="get" action="">
      <input id="artPlaceName" name="artPlaceName" size="25" />
      <input type="submit"/>
  </form>
';


formajax.js


$(document).ready(function () {
        function createNewForm() {
        $.ajax({
            url: 'futureForm.php',
            success: function (data) { // crude simulation of ajax load
                $('#newFormDiv').html(data);
            },
            complete: function () {
                $('#commentForm').validate({ // initialize the plugin
                    rules:{
                        artPlaceName:
                            {
                                required: true,
                                minlength: 2
                            }

                    },
        messages:{
            artPlaceName:
                        {
                            required: "<li>Please enter a name.</li>",
                            minlength: "<li>Your name is not long enough.</li>"
                        }
                    }
                });
            }
        });
    };

    $('button').click(function () {
        createNewForm();
    });

});

No comments:

Post a Comment