无法使用jQuery On Click方法提交表单

时间:2018-02-04 08:41:47

标签: javascript jquery jquery-forms-plugin

使用jQuery Form,出于某种原因,我必须通过jQuery on方法提交表单,如下所示:

$("#submitImage").on("click", function() {
   $('#loaderForm').ajaxForm(function() {
      alert("Uploaded SuccessFully");
   }); 
});

但这不是提交表格!你能看看这个演示,让我知道我在这里缺少什么或做错了吗?

 $("#uploadFile").change(function() {
     $('#image_preview').html("");
     var total_file=document.getElementById("uploadFile").files.length;

     for(var i=0;i<total_file;i++)
     {
        $('#image_preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
     }
  });
  
  $("#submitImage").on("click", function() {
     $('#loaderForm').ajaxForm(function() 
     {
         console.log("Uploaded SuccessFully");
     }); 
});
input[type=file]{
  display: inline;
}
#image_preview{
  border: 1px solid black;
  padding: 10px;
}
#image_preview img{
  width: 200px;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script>
<div class="container">

  <form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
      <input type="file" id="uploadFile" name="uploadFile[]" multiple/>
     
  </form>


  <br/>
  <button type="button" class="btn btn-success" id='submitImage' >Upload Image </button>
  <div id="image_preview"></div>
</div>

2 个答案:

答案 0 :(得分:0)

按钮类型应为&#39;提交&#39;

 <button type="submit" class="btn btn-success" id='submitImage' >Upload Image </button>

答案 1 :(得分:0)

移动<form>标记内的提交按钮,其类型应为submit

<form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFile" name="uploadFile[]" multiple/>
  <input type="submit" class="btn btn-success" id='submitImage' value='Upload Image' />
</form>

否则,您只需在按钮点击事件中调用$('#loaderForm').submit();;

<form id="loaderForm" action="uploadFile.php" method="post" enctype="multipart/form-data">
  <input type="file" id="uploadFile" name="uploadFile[]" multiple/>

</form>

<button type="button" 
onclick="javascript:function(){ $('#loaderForm').submit(); }"
class="btn btn-success" id='submitImage' >Upload Image 
</button>