取消下拉列表更改事件时如何设置以前的值

时间:2011-07-20 06:27:49

标签: javascript jquery html

我正在设计一个html页面。 我想显示一个关于使用jquery或javascript更改下拉元素的确认消息。 请帮忙。

我有要求确认的代码。选择取消时,它不会选择下一个项目。

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

由于

4 个答案:

答案 0 :(得分:9)

您应该能够将以前的值存储在click事件中,并将其设置回更改事件:

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

请参阅:http://jsfiddle.net/w9JYX/14/

更新:我更新了代码,使其在一组下拉控件上更加通用,并且还删除了单击处理程序。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

在不必创建全局变量或其他函数的情况下,这是相同行的更紧凑的解决方案:

$('#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"));
        }
    });

答案 3 :(得分:0)

ASP.NET页面的用法:

$("#<%= 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"));
    }
});