Paul
Paul

Reputation: 11746

Can I trigger a form action after selecting an image file for upload?

I currently have a form that lets a user select an image. After the image has been selected they need to click the submit button. I'm using jquery so the call ends up looking like this:

$('#image_form').ajaxForm(function(data) { 
   // do some stuff
});

here is the HTML:

<form id="image_form" enctype="multipart/form-data" action="load_photo.php" method="post" >
    <input type="hidden" name="MAX_FILE_SIZE" value="8000000" />

    <table>    
        <tr>
            <td>
                <label for="mapimage">Select an image:</label>
            </td>
        </tr>
        <tr>
            <td>
                <input name="file" type="file" id="file"/>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="Update" name="update_photo" id="update_photo"/>
            </td>
        </tr>
    </table>
</form>

Is it possible to trigger this form action after a user has browsed to a photo and selected it? Ideally they would not have to click the submit button.

Upvotes: 3

Views: 2677

Answers (2)

Tomas Reimers
Tomas Reimers

Reputation: 3292

As said above you can bind the change event, however you cannot detect what file they have selected or even the name of that file in some browsers cough older ie's I believe cough.

What you can do is to get the name of the file ($("#fileinput").val()) then parse the string at the last period:

// on change
{
    var fileParts = $("#fileinput").val().split(".");
    var extension = fileParts[fileParts.length - 1];
    var validFileExt = new Array("jpg", "jpeg", "bmp", "png", "gif");
    var isImage = jQuery.inArray(extension, validFileExt);
    if (isImage){
        // submit
    }
}

BTW I just made up that code so dbl check it

Of course you still need to offer a traditional button for Those browsers.

Also, this is not a valid file validation ;)

Upvotes: 0

Francis Avila
Francis Avila

Reputation: 31621

When a file has been selected, the change event fires on the input[type=file] element, so just listen for that.

$('#file').change(function(e){
    // do something after a file is selected
    // maybe submit the file?
    e.target.form.submit();
});

Upvotes: 5

Related Questions