我想要实现的事情是,每当<select>下拉菜单被更改时,我想要更改前的下拉菜单的值。我使用1.3.2版本的jQuery和使用的变化事件,但我在那里得到的值是变化后。

<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>

让我们说当前选项My现在被选中,当我在onchange事件中将其更改为堆栈时(即当我将其更改为堆栈时),我想要它之前的值,即在这种情况下我的期望。

如何实现这一目标?

编辑:在我的情况下,我有多个选择框在同一页,并希望同样的事情被应用到所有他们。也所有我的选择后插入页面加载通过ajax。


当前回答

(function() {

    var value = $('[name=request_status]').change(function() {
        if (confirm('You are about to update the status of this request, please confirm')) {
            $(this).closest('form').submit(); // submit the form
        }else {
            $(this).val(value); // set the value back
        }
    }).val();
})();

其他回答

如何使用一个自定义的jQuery事件与角手表类型的接口;

// adds a custom jQuery event which gives the previous and current values of an input on change
(function ($) {
    // new event type tl_change
    jQuery.event.special.tl_change = {
        add: function (handleObj) {
            // use mousedown and touchstart so that if you stay focused on the
            // element and keep changing it, it continues to update the prev val
            $(this)
                .on('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
                .on('change.tl_change', handleObj.selector, function (e) {
                // use an anonymous funciton here so we have access to the
                // original handle object to call the handler with our args
                var $el = $(this);
                // call our handle function, passing in the event, the previous and current vals
                // override the change event name to our name
                e.type = "tl_change";
                handleObj.handler.apply($el, [e, $el.data('tl-previous-val'), $el.val()]);
            });
        },
        remove: function (handleObj) {
            $(this)
                .off('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
                .off('change.tl_change', handleObj.selector)
                .removeData('tl-previous-val');
        }
    };

    // on focus lets set the previous value of the element to a data attr
    function focusHandler(e) {
        var $el = $(this);
        $el.data('tl-previous-val', $el.val());
    }
})(jQuery);

// usage
$('.some-element').on('tl_change', '.delegate-maybe', function (e, prev, current) {
    console.log(e);         // regular event object
    console.log(prev);      // previous value of input (before change)
    console.log(current);   // current value of input (after change)
    console.log(this);      // element
});

使用以下代码,我已经测试了它和它的工作

var prev_val;
$('.dropdown').focus(function() {
    prev_val = $(this).val();
}).change(function(){
            $(this).unbind('focus');
            var conf = confirm('Are you sure want to change status ?');

            if(conf == true){
                //your code
            }
            else{
                $(this).val(prev_val);
                $(this).bind('focus');
                return false;
            }
});

下面是一个简单的解决方案,没有jQuery、DOM遍历、事件绑定、全局变量等开销。它提示用户用包含“before”和“after”值的消息确认更改,并根据用户的选择取消或接受更改。

<select name="test" 
  onfocus="handleOnFocus(this);" 
  onchange="if(handleOnChange(this) == false) { return false; }"
  data-original-selected-index="">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>


// Prompt user to confirm the change
function handleOnChange(selectObj) {
  var confirmationMessage = 'Change ' +
    selectObj.options[selectObj.dataset.originalSelectedIndex].text + 
    ' to ' + 
    selectObj.options[selectObj.selectedIndex].text + '?';

  if (!confirm(confirmationMessage)) {
    selectObj.selectedIndex = selectObj.dataset.originalSelectedIndex;
    return false;
  } else {
    selectObj.dataset.originalSelectedIndex = selectObj.selectedIndex;
    return true;
  }
}

// Initialize original selected index (one-time)
function handleOnFocus(selectObj) {
  if (selectObj.dataset.originalSelectedIndex == '') {
    selectObj.dataset.originalSelectedIndex = selectObj.selectedIndex;
  }
}

JSFiddle在这里: https://jsfiddle.net/humbads/f3a0v8ys/

注1:onchange处理程序是这样编写的,所以这个解决方案也可以与ASP一起工作。Net下拉列表控件与AutoPostBack=True和OnSelectedIndexChanged处理程序。

注意2:选项不应该包含空值。如果存在,则更改初始值。

我想为解决这个问题贡献另一种选择;因为上面提出的解决方案并没有解决我的情况。

(function()
    {
      // Initialize the previous-attribute
      var selects = $('select');
      selects.data('previous', selects.val());

      // Listen on the body for changes to selects
      $('body').on('change', 'select',
        function()
        {
          $(this).data('previous', $(this).val());
        }
      );
    }
)();

这确实使用了jQuery,所以def.在这里是一个依赖项,但这可以在纯javascript中进行调整。(在body中添加监听器,检查原始目标是否为select, execute函数,…)

通过将更改侦听器附加到主体,您几乎可以确定它将在特定的侦听器之后触发选择,否则'data-previous'的值将在您甚至可以读取它之前被覆盖。

当然,这是假设您更喜欢为set-previous和check-value使用单独的侦听器。它正好符合单一责任模式。

注意:这将把“先前”功能添加到所有选择中,所以如果需要,请确保对选择器进行微调。

在编写下拉“on change”动作函数之前,将当前选中的jquery下拉值保存在全局变量中。 如果你想在函数中设置之前的值,你可以使用全局变量。

//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
  function (result) {
  if (result) {
     return true;
  } else {
      $("#dropDownList").val(previousValue).trigger('chosen:updated');  
     return false;
         }
  });
});