代码之家  ›  专栏  ›  技术社区  ›  Alpesh

获取更改前的选择值(下拉列表)

  •  209
  • Alpesh  · 技术社区  · 14 年前

    我想实现的是 <select> 下拉列表已更改我希望在更改前下拉列表的值。我使用的是1.3.2版本的jQuery和on change事件,但是我得到的值是在更改之后。

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

    如何才能做到这一点?

    在我的例子中,我在同一个页面中有多个选择框,并且希望对所有选择框应用相同的东西。另外,在通过ajax加载页面后插入所有选定内容。

    16 回复  |  直到 5 年前
        1
  •  425
  •   Dimitar Dimitrov    10 年前

    合并 改变

    (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

        2
  •  133
  •   Piotr Kula David Boike    11 年前

    请不要对此使用全局变量-将上一个值存储在数据中 下面是一个例子: http://jsbin.com/uqupu3/2/edit

    $(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值

        3
  •  81
  •   Himanshu THE ONLY ONE    12 年前

    jquery.data()

    使用焦点不是有效的解决方案。它在第一次更改选项时起作用,但如果您停留在该select元素上,并按“up”或“down”键。它不会再通过焦点事件。

    所以解决办法应该是如下所示,

    //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
    })
    
        4
  •  8
  •   August Lilleaas    14 年前

    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;
      });
    });
    
        5
  •  6
  •   cs95 abhishek58g    7 年前
     $("#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());
    });
    
        6
  •  3
  •   Cica Gustiani    10 年前

    我使用的是事件“live”,我的解决方案基本上与Dimitiar类似,但不是使用“focus”,而是在触发“click”时存储以前的值。

    var previous = "initial prev value";
    $("select").live('click', function () {
            //update previous value
            previous = $(this).val();
        }).change(function() {
            alert(previous); //I have previous value 
        });
    
        7
  •  2
  •   Deshani Tharaka    8 年前

    在编写下拉“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;
             }
      });
    });
    
        8
  •  1
  •   Nick M    8 年前

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

    示例代码如下:

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

    我忘记在元素中添加.clone()。如果不这样做,当您试图拉回值时,您最终会拉入选择的新副本,而不是上一个副本。使用clone()方法存储select的副本,而不是它的实例。

        10
  •  0
  •   Soufiane Hassou    14 年前

    那么,为什么不存储当前选定的值,当选定的项更改时,将存储旧值?(您可以根据需要重新更新)

        11
  •  0
  •   Er.KT    11 年前

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

    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;
                }
    });
    
        12
  •  0
  •   Bilal    10 年前
    (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();
    })();
    
        13
  •  0
  •   thisisboris    8 年前

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

    (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函数,…)。

    通过将更改侦听器附加到主体,您可以非常确定这将触发 之后

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

    注: 全部的 选择,因此如果需要,请确保微调选择器。

        14
  •  0
  •   ermSO    7 年前

    这是对“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() );
            }
        );
    })();
    
        15
  •  0
  •   ViES    7 年前

    最佳解决方案:

    $('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);
    });
    
        16
  •  0
  •   Rishi Alluri    6 年前

    有几种方法可以达到你想要的结果,这是我谦卑的方法:

    让元素保留其前一个值,因此添加一个属性“previousValue”。

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

    一旦初始化,“previousValue”现在可以用作属性。在JS中,要访问此select的previousValue:

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

    使用“previousValue”完成后,将属性更新为当前值。

        17
  •  0
  •   Dieter Gribnitz    5 年前

    我需要根据选择显示不同的div

    HTML格式

    <select class="reveal">
        <option disabled selected value>Select option</option>
        <option value="value1" data-target="#target-1" >Option 1</option>
        <option value="value2" data-target="#target-2" >Option 2</option>
    </select>
    <div id="target-1" style="display: none">
        option 1
    </div>
    <div id="target-2" style="display: none">
        option 2
    </div>
    

    $('select.reveal').each((i, element)=>{
        //create reference variable 
        let $option = $('option:selected', element)
        $(element).on('change', event => {
            //get the current select element
            let selector = event.currentTarget
            //hide previously selected target
            if(typeof $option.data('target') !== 'undefined'){
                $($option.data('target')).hide()
            }
            //set new target id
            $option = $('option:selected', selector)
            //show new target
            if(typeof $option.data('target') !== 'undefined'){
                $($option.data('target')).show()
            }
        })
    })
    
    推荐文章