Вопрос

I need the same form to be submitted whether the user clicks on the submit button or selects a file to upload. I also need a warning to confirm if the user wants to navigate away without saving.

See http://jsfiddle.net/fuW2j/

When the submit button is clicked, the beforeunload event is unbound.

How can I make this happen for the file upload as well?

Это было полезно?

Решение

DEMO

HTML

<input type="file"/>

js

$('input:file').change(function () {
    $(window).unbind('beforeunload');
    this.form.submit();
});

.change()

Другие советы

Instead of inline pure JavaScript, handle the file change with jQuery too:

$('input[type="file"]').change(function() {
    $(this).parents("form").eq(0).trigger("submit");
});

And have only this:

<input type="file"/>

Updated fiddle.

Using $('input').change(...) seems to work fine : http://jsfiddle.net/fuW2j/8/

(function() {

    $(window).bind('beforeunload', function() {
        return 'Your changes have not been saved!';
    });

    $('input').change(function() {
        //$(window).unbind('beforeunload');
        $(this).closest('form').submit();
    });
    $('form').submit(function() {
        $(window).unbind('beforeunload');
    });
})(jQuery);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top