Search code examples
javascriptjqueryhtmljquery-file-upload

How to send additional form fields using jquery file upload


I'm using jquery file upload to upload files to server side action. However, I would like to also send additional form fields as part of the form submit. Additionally, I want the formsubmit to happen only when the "submit" button is clicked.

Is this doable using jquery file upload?

I've created a jsbin: http://jsbin.com/mozujilede/1/edit?html,js,output

Desired behavior:

  • user should be alerted if they try to upload more files than allowed limit
  • additional form data should be sent to the server side along with multiple files
  • the form submit should happen only when user clicks submit button.

This is what I'm doing at the moment:

var maxFiles = 10;
$('#fileupload').fileupload({
    singleFileUploads: false,
    url: '/uploadUrl'
}).bind('fileuploadadd', function (e, data) {
        var input = $('#input');
        data.formData = {example: input.val()};
        var fileCount = data.files.length;
        if (fileCount > maxFiles) {
            alert("The max number of files is "+maxFiles);
            return false; 
        }
    });

Solution

  • Try This

    var byButton = false;
    $("#sub-but").on("click",function(){
      var inp = $("#files")[0];
      if(inp.files.length > 10){
        alert("Max number of files");
        return false;
      }
      byButton = true;
      $("#myForm").submit();
    });
    function validate(){
      if(!byButton)
         return false;
      byButton = false;
      return true;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="myForm" onsubmit="return validate();">
      <input type="text" placeholder="some extra items"/>
      <input type="file" id="files" multiple="multiple"/>
      <input type="button" value="Submit" id="sub-but"/>
    </form>