Search code examples
javascriptjqueryvalidationclone

Validation on a cloned form


I have a form which is cloned using jquery. Because it is cloned, the validation does not work properly.

I have managed to get it give an alert when the field is not filled in, but it still submits the form after the alert message is cleared.

Any ideas?

Code below...

$(document).ready(function(){
   $("ul > li > a").click(function() {
       $popupCopy = $("." + $(this).attr("href")).html();
       $popupAddClass = $(this).attr("href");
       $popupWidth = parseFloat($("." + $(this).attr("href")).attr("title")) + 80;
       $("<div class='popupContainer'><div class='popupContent " + $popupAddClass + "'>" + $popupCopy + "</div><img src='images/close.png' class='closePopup'></div>").appendTo("body");
       $(".popupContainer").fadeIn(500);
       return false;
   });

   $(".giftName").live("focus", function() {
       if ( $(this).val()=="Name") {
            $(this).val('');
       };
   });

   $(".giftName").live("blur", function() {
       if ( $(this).val()=="") {
            $(this).val('Name');
       };
   });

   $('.giftSubmit').live('click', function(){  
       if( ! checkvalid() ) {  
           alert('Need to fill-out all fields')  
       }  
       else {  
           alert('Thanks')  
       }  
   });

});

function checkvalid(){
   var valid = true;
   $('.giftName').each(function(){
       if (this.value == '' || this.value == 'Name' || this.value == null) {
           valid = false;
           return;
       }
   })
   return valid;
}

body:

<div class="pageContainer">
    <div class="bodyPanel">   
        <ul>
            <li><a href="giftlist">Gift list</a></li>
        </ul>   
    </div>
</div>

<div class="popupsHidden">
    <div class="giftlist">
        <form action="sendGift.php" class="giftForm" method="post">
            <input name="giftName" class="giftName" type="text" value="Name" />
            <input name="" class="giftSubmit" type="submit" value="Send your promised gift..." />
        </form>
    </div>
</div>

Solution

  • Instead of listening for the click event on the submit button, try listing for the submit event on the form itself:

    $('.giftForm').live('submit', function() {
        if ( ! checkValid() ) {
            alert('not valid !');
            return false;
        }
    });