how to prevent to change selectbox value if i say no to confirm

Below solution worked for me. First of all onfocus is called. This event keeps the current value in a attribute "PrvSelectedValue". Secondly onchange is called, we set the previous value if user cancel the confirmation popup.return false is used to prevent the postback in ASP.NET.

<select   
onfocus="this.setAttribute('PrvSelectedValue',this.value);" 

onchange="if(confirm('Do you want to change?')==false){ this.value=this.getAttribute('PrvSelectedValue');return false; }" 

></select>

I'm posting this reply at the risk of ridicule because I'm admittedly pretty noob at this stuff (only been learning a month or two), but I was able to handle a similar situation (changing time zones) just doing this:

$(".timezonedropdown").change(function() {
    var newVal = $(this).val();
    if(!confirm("Are you sure?")) {
        $(this).val($(this).closest('select').attr("data-originaltimezone"));
    }
});

Then in my html I included data-originaltimezone="whatever" in the select. I had the class timezonedropdown for the select as well. Hope that helps! :)


You can just store the previous value and set it back if needed, like this:

var countryVal;
$("#country").change(function() {
  var newVal = $(this).val();
  if (!confirm("Are you sure you wish to destroy these country branches?")) {
    $(this).val(countryVal); //set back
    return;                  //abort!
  }
  //destroy branches
  countryVal = newVal;       //store new value for next time
});

Or use .data() as @Gaby suggests, like this:

$("#country").change(function() {
  var newVal = $(this).val();
  if (!confirm("Are you sure you wish to destroy these country branches?")) {
    $(this).val($.data(this, 'val')); //set back
    return;                           //abort!
  }
  //destroy branches
  $.data(this, 'val', newVal);        //store new value for next time
});