jQuery - cancel change event on confirmation dialog for a Dropdown

Viewed 59020

I have a dropdown and I have the jQuery change function.

I would like to implement the change of the selected item as per the Confirmation dialog.

If confirms true i can proceed for selected change otherwise I have keep the existing item as selected and cancel the change event.

How can I implement this with jQuery?

jquery Function

$(function () {
    $("#dropdown").change(function () {
        var success = confirm('Are you sure want to change the Dropdown ????');
        if (success == true) {
            alert('Changed');  
            // do something                  
        }
        else {
            alert('Not changed');
            // Cancel the change event and keep the selected element
        }
    });
});

One thing to remember change function hits only after selected item changed So better to think to implement this on onchange - but it is not available in jquery. Is there any method to implement this?

7 Answers

As far as I know you have to handle it yourself, this might help:

<select onFocus="this.oldIndex = this.selectedIndex" onChange="if(!confirm('Are you sure?'))this.selectedIndex = this.oldIndex">

Simply do it like

$("#dropdown").change(function () {
    var success = confirm('Are you sure want to change the Dropdown ????');
    if (success == true) {
        // do something                  
    }
    else {
        return false; // will set the value to previous selected
    }
}); 
Related