2011-07-20 24 views
6

我正在设计一个html页面。 我想显示一个确认信息,使用jQuery或JavaScript更改下拉元素。 请帮忙做到这一点。如何在取消下拉列表更改事件时设置以前的值

我有要求确认的代码。在选择取消时,它不会选择以前的下拉项目。

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

感谢

+0

你测试吗?我没有,但我认为它会奏效。编辑:你提供的代码完美的作品。什么是问题? – Vithozor

+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/

更新:我更新了代码以更一般地处理一组下拉控件,并且还删除了点击处理器。

+0

这工作正常。 非常感谢你 –

+1

使用'.data()'而不是那个变量会更优雅。 – kapa

+0

如何通过“this”而不是lastSelected = $(“#dropdownId option:selected”);因为我有多个调用相同函数的下拉元素 –

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

实际上比这更像我的解决方案,因为您不需要干扰点击事件。 –

0

这里是沿着相同的路线有点更紧密的解决方案,而无需创建全局变量或其它功能:

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