onclick event doesn't wait for file selection

260
November 21, 2016, at 6:43 PM

I am trying to use file input in html using a single button.

My html:

<input type="file" class="btn btn-purple" id="inventory_csv" name="inventory_csv" onchange="this.form.submit()" style="display:none">
<button name="upload_inventory" id="upload_inventory" class="btn btn-purple btn-labeled fa" onclick="chooseFile()">Upload Inventory</button>

Javascript:

<script>
    function chooseFile() {
        $("#inventory_csv").click();
    }
</script>

The script doesn't work properly. When I click the upload_inventory button, it does not wait for me to select the file. It opens the file selection dialog box and navigates to the next page.

I want it to wait for me to select the file and then go to the next page.

Answer 1

Default behavior of button is submit, set its type to button

<button type="button" onclick="chooseFile()">Upload Inventory</button>

OR, Prevent its default behaviour like

<button onclick="return chooseFile()">Upload Inventory</button>

Script

function chooseFile() {
     $("#inventory_csv").click();
     return false;
}
Answer 2

You can detect if a file was selected and submit the form afterwards.

  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       //submit form or whatever
     });
  });
Answer 3

As Satpal mentionned it, what happens is that the button default behavior is also triggered and submits the form.

You can either prevent default behavior or change the button type:

<button type="button" ...></button>

Or

function chooseFile() {
    $("#inventory_csv").click();
    return false;
}
Rent Charter Buses Company
READ ALSO
Filtering google map markers with Knockout.js

Filtering google map markers with Knockout.js

I'm trying to use a hide google maps markers using a search bar. I only want matches to show on the map, and I want non-matches to be hidden.

512
How do I execute a form with PHP after jQuery submit()

How do I execute a form with PHP after jQuery submit()

This is the first time I'm submitting a form with jQuery. .

403
Add/remove class on scroll with waypoints

Add/remove class on scroll with waypoints

I am trying to add a class to each section, using jquery waypoints. [nnn]The point is that the class 'fixed', is to be added, when the section hits the top of the viewpoint, and then remove the class again for the previous section.

539