Tom
Tom

Reputation: 12998

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>

Upvotes: 0

Views: 1096

Answers (2)

counsellorben
counsellorben

Reputation: 10924

In your $('.giftSubmit').live('click' ... function, you need to add return false; after showing your validation failure message. This will stop the event from propagating.

Because the click event is not being stopped, the form is being submitted, despite the validation failure.

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

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;
    }
});

Upvotes: 2

Related Questions