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?
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; } });
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); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With