开发者

Validation on a cloned form

开发者 https://www.devze.com 2023-04-02 07:51 出处:网络
I have a form which is cloned using jquery. Because it is cloned, the validation does not work properly.

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(5开发者_StackOverflow中文版00);
       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>


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消