2015-07-10 40 views
0

我有這樣的形式非常簡單的工作:不能得到JQuery驗證與jQuery給ajaxForm和進度條

<form id="file-form" action="student-files.php?userId=<?php echo $userId ;?>" method="post" enctype="multipart/form-data"> 

<strong>Title:</strong><br /> 
<input type="text" name="title" id="title" value=""> 
<span id="invalid-title" class="errormsg"></span> 
<br /><br /> 

<strong>File:</strong><br /> 
<input type="file" name="file1" id="file1" value="null"> 
<span id="invalid-file1" class="errormsg"></span> 
<br /><br /> 

<div class="progress"> 
    <div class="bar"></div > 
    <div class="percent">0%</div > 
</div> 
<div id="status"></div> 
<br /><br /> 

<input type="submit" name="submit" value="Add File"> 
</form> 

我試圖使用驗證,並給ajaxForm在同一時間,這樣我可以有一個上傳進度條。我在這裏發現了幾個類似的答案,但他們都沒有爲我工作。

如果我完全刪除驗證呼叫,那麼進度條更新和文件上傳。如果我保持validate調用,則進度條不會更新,但文件不會上載。

這只是進度條的視覺部分,不工作,我不能爲我的生活弄明白。

這裏是我的JS

<script type="text/javascript"> 

$(document).ready(function() { 

    $('#file-form').validate({ 
     rules: { 
      file1: { 
       required: true, 
       extension: "pdf", 
      }, 
     }, 
     messages: { 
      file1: "File must be PDF", 
     }, 
     onkeyup: false, 
     onfocusout: false, 
     onclick: false, 
     errorPlacement: function(error, element) { 
     error.appendTo('#invalid-' + element.attr('id')); 
    } 
    }); 

    var bar = $('.bar'); 
    var percent = $('.percent'); 
    var status = $('#status'); 


    $('#file-form').ajaxForm({ 
     beforeSubmit: function() { 
      status.empty(); 
      var percentVal = '0%'; 
      bar.width(percentVal) 
      percent.html(percentVal); 
      return $('#file-form').valid(); 
     }, 
     uploadProgress: function (event, position, total, percentComplete) { 
      var percentVal = percentComplete + '%'; 
      bar.width(percentVal) 
      percent.html(percentVal); 
     }, 
     complete: function() { 
      bar.width("100%"); 
      percent.html("100%"); 
      window.location.replace("student-files.php?userId=<?php echo $userId ;?>") 
     } 
    }); 
}); 

</script> 

任何幫助將不勝感激。

回答

0

您只需將您的ajaxForm()函數放入jQuery Validate插件的submitHandler回調選項中即可。 As per the documentationsubmitHandler「經過驗證通過Ajax提交表單的正確位置」

更多的東西像這樣...

$(document).ready(function() { 

    $('#file-form').validate({ 
     rules: { 
      file1: { 
       required: true, 
       extension: "pdf", 
      }, 
     }, 
     messages: { 
      file1: "File must be PDF", 
     }, 
     onkeyup: false, 
     onfocusout: false, 
     onclick: false, 
     errorPlacement: function(error, element) { 
      error.appendTo('#invalid-' + element.attr('id')); 
     }, 
     submitHandler: function(form) { 
      $(form).ajaxForm({ 
       // your options 
      }); 
      return false; 
     } 
    }); 

});