Royal Pinto
Royal Pinto

Reputation: 2911

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

Upvotes: 9

Views: 12941

Answers (4)

RFE Petr
RFE Petr

Reputation: 694

Usage for ASP.NET page:

$("#<%= dropdownId.ClientID %>")
.on('focus', function () {
    $(this).data("prev", $(this).val());
})
.change(function () {
    if (confirm('Are you sure?')) {
        $(this).data("prev", $(this).val());
    } else {
        $(this).val($(this).data("prev"));
    }
});

Upvotes: 0

DShook
DShook

Reputation: 15664

Here's a bit tighter solution along the same lines without having to create global variables or other functions:

$('#dropdownId')
    .on('focus', function () {
        $(this).data("prev", $(this).val());
    })
    .change(function () {
        if (confirm('Are you sure?')) {
            //normal case where the dropdown changes
            $(this).data("prev", $(this).val());
        } else {
            //if the user doesn't confirm reset the dropdown back to what it was
            $(this).val($(this).data("prev"));
        }
    });

Upvotes: 3

Can Gencer
Can Gencer

Reputation: 8885

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.

Upvotes: 9

Shef
Shef

Reputation: 45589

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;
    }
});

Upvotes: 2

Related Questions