Alex Rivera | Logout

How to set previous value when cancelling a drop-down list change event

Asked 2011-07-20T06:27:49.263
9

I am designing a html page. I want to show a confirmation msg on changing a drop down element using jquery or javascript. Please help to do this.

I have code which will ask confirmation. On selecting cancel it will not select previous item of Drop down.

$("#dropdownId").change(function(e) 
{
        if($(this).val() == "40")
        {
            if(confirm("Are you sure"))
                return true;
            else
                return false;
        }
});

Thanks

Edit
Report

1 Answer

9

You should be able to store the previous value on the click event and set it back on the change event:

var setLastSelected = function(element) {
   $(element).data('lastSelected', $(element).find("option:selected"));
};

$("select").each(function () {
   setLastSelected(this);
});

$("select").change(function(){        
      if(confirm("Are you sure")) { 
          setLastSelected(this);
          return true; 
      }
      else {
         $(this).data('lastSelected').attr("selected", true);
         return false;
      }
});

See: http://jsfiddle.net/w9JYX/14/

Update: I updated the code to work more generically on a set of dropdown controls and also removed the click handler.

answered 2011-07-20T06:39:41.927

Your Answer