首页 文章

在更改之前获取select(下拉列表)的值

提问于
浏览
197

我想要实现的是每当 <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事件中将其更改为堆栈时(即当我将其更改为堆栈时)我想要它的先前值,即我在这种情况下的预期 .

怎么能实现这一目标?

Edit: 在我的情况下,我在同一页面中有多个选择框,并希望将相同的内容应用于所有这些框 . 此外,我的所有选择都是在通过ajax加载页面后插入的 .

16 回答

  • 1

    在写下“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;
             }
      });
    });
    
  • 0

    将焦点事件与更改事件相结合,以实现您的目标:

    (function () {
        var previous;
    
        $("select").on('focus', function () {
            // Store the current value on focus and on change
            previous = this.value;
        }).change(function() {
            // Do something with the previous value after the change
            alert(previous);
    
            // Make sure the previous value is updated
            previous = this.value;
        });
    })();
    

    工作示例:http://jsfiddle.net/x5PKf/766

  • 72

    请不要使用全局变量 - 存储此处数据的prev值是一个示例:http://jsbin.com/uqupu3/2/edit

    ref的代码:

    $(document).ready(function(){
      var sel = $("#sel");
      sel.data("prev",sel.val());
    
      sel.change(function(data){
         var jqThis = $(this);
         alert(jqThis.data("prev"));
         jqThis.data("prev",jqThis.val());
      });
    });
    

    只是看到你在页面上有很多选择 - 这种方法也适用于你,因为对于每个选择你将把prev值存储在select的数据上

  • 0

    我选择使用 jquery.data() 的Avi Pinto解决方案

    使用焦点不是有效的解决方案 . 它在您第一次更改选项时有效,但如果您保持选择元素,则按“向上”或“向下”键 . 它不会再次通过焦点事件 .

    所以解决方案应该更像下面这样,

    //set the pre data, usually needed after you initialize the select element
    $('mySelect').data('pre', $(this).val());
    
    $('mySelect').change(function(e){
        var before_change = $(this).data('pre');//get the pre data
        //Do your work here
        $(this).data('pre', $(this).val());//update the pre data
    })
    
  • 0

    手动追踪 Value .

    var selects = jQuery("select.track_me");
    
    selects.each(function (i, element) {
      var select = jQuery(element);
      var previousValue = select.val();
      select.bind("change", function () {
        var currentValue = select.val();
    
        // Use currentValue and previousValue
        // ...
    
        previousValue = currentValue;
      });
    });
    
  • 0
    $("#dropdownId").on('focus', function () {
        var ddl = $(this);
        ddl.data('previous', ddl.val());
    }).on('change', function () {
        var ddl = $(this);
        var previous = ddl.data('previous');
        ddl.data('previous', ddl.val());
    });
    
  • 1

    我正在使用事件“实时”,我的解决方案基本上与Dimitiar类似,但不是使用“焦点”,而是在触发“点击”时存储我之前的值 .

    var previous = "initial prev value";
    $("select").live('click', function () {
            //update previous value
            previous = $(this).val();
        }).change(function() {
            alert(previous); //I have previous value 
        });
    
  • 3

    如何使用带有角度监视类型接口的自定义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
    });
    
  • 8

    我知道这是一个老线程,但我想我可能会增加一些额外的东西 . 在我的情况下,我想传递文本,val和一些其他数据attr . 在这种情况下,最好将整个选项存储为prev值而不仅仅是val .

    示例代码如下:

    var $sel = $('your select');
    $sel.data("prevSel", $sel.clone());
    $sel.on('change', function () {
        //grab previous select
        var prevSel = $(this).data("prevSel");
    
        //do what you want with the previous select
        var prevVal = prevSel.val();
        var prevText = prevSel.text();
        alert("option value - " + prevVal + " option text - " + prevText)
    
        //reset prev val        
        $(this).data("prevSel", $(this).clone());
    });
    

    EDIT:

    我忘了将.clone()添加到元素上 . 如果你没有这样做,当你试图拉回你最终拉入选择的新副本而不是之前的副本 . 使用clone()方法存储select的副本而不是它的实例 .

  • 6

    那么,为什么不存储当前选定的值,并且当所选项目被更改时,您将存储旧值? (您可以根据需要再次更新)

  • 0

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

    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;
                }
    });
    
  • 0
    (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();
    })();
    
  • 1

    我想提出另一个选择来解决这个问题;因为上面提出的解决方案并没有解决我的问题 .

    (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 . (向主体添加侦听器,检查原始目标是否为select,execute function,...) .

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

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

    Note: 这会将'previous'功能添加到 all 选项中,因此请务必根据需要微调选择器 .

  • 124

    这是对@thisisboris答案的改进 . 它为数据添加了当前值,因此代码可以控制何时更改设置为当前值的变量 .

    (function()
    {
        // Initialize the previous-attribute
        var selects = $( 'select' );
        $.each( selects, function( index, myValue ) {
            $( myValue ).data( 'mgc-previous', myValue.value );
            $( myValue ).data( 'mgc-current', myValue.value );  
        });
    
        // Listen on the body for changes to selects
        $('body').on('change', 'select',
            function()
            {
                alert('I am a body alert');
                $(this).data('mgc-previous', $(this).data( 'mgc-current' ) );
                $(this).data('mgc-current', $(this).val() );
            }
        );
    })();
    
  • 386

    最佳方案:

    $('select').on('selectric-before-change', function (event, element, selectric) {
        var current = element.state.currValue; // index of current value before select a new one
        var selected = element.state.selectedIdx; // index of value that will be selected
    
        // choose what you need
        console.log(element.items[current].value);
        console.log(element.items[current].text);
        console.log(element.items[current].slug);
    });
    
  • 0

    有几种方法可以实现您想要的结果,这是我谦虚的做法:

    让元素保持其先前的值,因此添加属性“previousValue” .

    <select id="mySelect" previousValue=""></select>
    

    初始化后,'previousValue'现在可以用作属性 . 在JS中,要访问此select的previousValue:

    $("#mySelect").change(function() {console.log($(this).attr('previousValue'));.....; $(this).attr('previousValue', this.value);}
    

    使用'previousValue'后,将属性更新为当前值 .

相关问题