如何在jQuery中保留DropDownList Onchange上的先前选择的值

时间:2014-12-10 05:36:26

标签: javascript jquery asp.net-mvc-4

 $(document).ready(function() {
        // Get the initial value
        var $el = $('#ddlCategoryName');
        $el.data('previousCategoryID', $el.val());


        $el.change(function() {
                //store new value
                var $this = $(this);
                var newValue = $this.data('newVal', $this.val());
            })
            .focus(function() {
                // Get the value when input gains focus
                var previousCategoryID = $(this).data('previousCategoryID');
            });
    });

大家好,我的要求是在下拉列表中选择新选项时始终跟踪上一个值。上面的示例代码仅适用于第一页加载,但从不适用于后续下拉列表选择更改。

是否有人知道我需要做的修改,以便在“ddlCategoryName”下拉列表中进行新选择时,使代码跟踪上一个选择的值。

我想在做出新选择后始终知道之前的值。

2 个答案:

答案 0 :(得分:0)

在更改事件处理程序中,您需要将当前值保存在previousCategoryID中。

var $el = $('#ddlCategoryName');
$el.data('previousCategoryID', $el.val());

$el.change(function() {
    //store new value
    var $this = $(this);
    var newValue = $this.data('newVal', $this.val());

    alert("previous: "+$this.data('previousCategoryID'));
    $this.data('previousCategoryID', $this.val());
});

请参阅DEMO

答案 1 :(得分:-1)

您可以在下拉列表的焦点事件中保留先前的值:

var previous;

$("#ddlCategoryName").focus(function () {
    // Store the current value 
    previous = this.value;
}).change(function() {
     console.log(previous);
    //Do something
});
相关问题