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

Hi all, my requirement is to always keep track of the previous value when a new option is selected in a dropdownlist. The sample code above works only on the first page load but never on subsequent dropdownlist selection changes.

Does any one know the modification i need to do to make the code track the value of the previous selection a very time a new selection is made in the "ddlCategoryName" dropdownlist.

I want to always know what the previous value after making a new selection.

StackTrace
  • 8,726
  • 33
  • 102
  • 188
  • how about pushing it all in a variable onchange? – roullie Dec 10 '14 at 05:39
  • In the `change` event, you need to reset the value of `previousCategoryID` to the current value (your currently setting it to `newVal` but never using it) –  Dec 10 '14 at 05:42

2 Answers2

0

In the change event handler, you need to save the current value in 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());
});

Please see DEMO

user2466202
  • 1,007
  • 9
  • 7
-1

You can retain the previous value in the focus event of the dropdown:

var previous;

$("#ddlCategoryName").focus(function () {
    // Store the current value 
    previous = this.value;
}).change(function() {
     console.log(previous);
    //Do something
});
user3263194
  • 433
  • 6
  • 19