user3510735
user3510735

Reputation:

how to call the onbeforeunload in link click event jquery?

I have the div tag with text box and outside the div I having one link button. * Im using the dataTable js and adding the custom column as "edit" link, its href="#"..

  1. If im click on the link without entering any data means it should not call the onbeforeunload function.

  2. After entering any data in textbox before clicking the save If im click on the link means it should call the onbeforeunload function. and have to show message like 'You haven\'t saved your changes'.

<div id="inputform">Description
  <input type="text" id="Description" placeholder="Enter the description..." name="description" />
  <input type="submit" value="save"/>
</div>
<a href='www.google.co.in'>link</a>                                   
$('#inputform').on('change keyup keydown', 'input, textarea, select', function (e) {
    $(this).addClass('changed-input');
});

$(window).on('beforeunload', function () {
    if ($('.changed-input').length) {
        return 'You haven\'t saved your changes.';
    }
});

http://jsfiddle.net/4fNCh/809/

Upvotes: 1

Views: 1794

Answers (1)

MrCode
MrCode

Reputation: 64526

Use a variable ie saved to track whether or not the save button was clicked. You can check this in the unload event:

Fiddle

var saved = true;

$(function () {
    $('input[type=submit]').click(function () {
        // do the saving...
        saved = true;
    });

    $('#inputform').on('change keyup keydown', 'input, textarea, select', function (e) {
        $(this).addClass('changed-input');
        saved = false;
    });

    $(window).on('beforeunload', function () {
        if (!saved) {
            if ($('.changed-input').length) {
                return 'You haven\'t saved your changes.';
            }
        }
    });
    $(document).on('click', 'a[href]', function () {
        if (!saved) {
            if ($('.changed-input').length) {
                return confirm('You haven\'t saved your changes.');
            }
        }
    });
})

Upvotes: 1

Related Questions