Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 354
Royal Pinto Avatar asked Jul 20 '11 06:07

Royal Pinto


2 Answers

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.

like image 96
Can Gencer Avatar answered Nov 24 '22 01:11

Can Gencer


var previous_option = $('#dropdownId option:selected');
$("#dropdownId").change(function(e){
    var $this = $(this),
        selected = $this.find('option:selected');
    if($this.val() == "40"){
        if(confirm("Are you sure")){
            previous_option = selected;
            return true;
        } else{
            selected.removeAttr('selected');
            previous_option.attr('selected', 'selected');
        }
    } else{
        previous_option = selected;
    }
});
like image 24
Shef Avatar answered Nov 24 '22 01:11

Shef