3

I am trying to implement upload file , I want to call the file input to select the file first, after selected the file , then will do form submit. However in my code , it will call form submit immediately. I have tried use ajax but not work. Any way I want to do the form submit just after the user have selected the file. But it seems cannot find a way to wait the finishing of the file input click function ( I mean until the user have selected a file)

Here is my html:

 <input type="text" id="body" name="body" >
 <button type="submit"  id="sent_1" value="Send">Submit</button>         
 <input type="file" id="image_file" name="image" size="chars">
 <button  id="send_img_btn" value="image">Image</button></td>

Here is my javascript:

    $('#send_img_btn').click(function(e){
          e.preventDefault();
    $('#image_file').click();
    $('#form').submit();
});

function imageClick(){
       $('#image_file').click();
}

function submit(){
       $('#form').submit();
}

Edited: Maybe I am not clearly saying my problem. The problem is that when
I click the button, it just submit the form instantly, not waiting me for selected file. I want it to wait me until I selected the file then submit.

1
  • 1
    If you intend to submit your form as soon as user selects a file, then use the input's change event to accomplish the same Commented Oct 19, 2016 at 10:29

2 Answers 2

7

Add attribute type="button" in <button> tag.

By default, <button> tag acts like <input type="submit"> inside <form> tag.

<button type="button" id="send_img_btn">Image</button>
Sign up to request clarification or add additional context in comments.

1 Comment

Fixed my issue!
2

If you want to submit the form as soon as the file is selected, use change event of that input.

<form action="formActionUrl" name="myForm">
   <input type="file" name="myInput"/>
</form>

In Script

$(":file").change(function(e){
     $("[name=myForm]").trigger('submit');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.