Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - cancel change event on confirmation dialog for a Dropdown

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?

like image 683
Vinu Avatar asked Jul 13 '11 10:07

Vinu


2 Answers

Well, as Vinu has rightly pointed out, jQuery's change event is only triggered once the value of the select has actually been changed. You would be better off doing something like this:

var prev_val;  $('#dropdown').focus(function() {     prev_val = $(this).val(); }).change(function() {      $(this).blur() // Firefox fix as suggested by AgDude     var success = confirm('Are you sure you want to change the Dropdown?');     if(success)     {         alert('changed');         // Other changed code would be here...     }       else     {         $(this).val(prev_val);         alert('unchanged');         return false;      } }); 
like image 166
BenM Avatar answered Sep 16 '22 18:09

BenM


Something like what I did here?

http://jsfiddle.net/Swader/gbdMT/

Simply save the value as soon as a user clicks the select box, and revert back to this value if the onchange confirmation returns false.

Here is the code from my fiddle:

var lastValue;  $("#changer").bind("click", function(e) {     lastValue = $(this).val(); }).bind("change", function(e) {     changeConfirmation = confirm("Really?");     if (changeConfirmation) {         // Proceed as planned     } else {         $(this).val(lastValue);     } }); 
like image 31
Swader Avatar answered Sep 16 '22 18:09

Swader