3

Is it possible to get the previous value from the OnChange event from a drop down? I need to see the previous selected value, so that I can make a decision on what I should display.

At the moment, I get the new value:

var id = $('.cmbType').val();

But would like to know what it was before the user selected this value.

Craig
  • 15,856
  • 29
  • 129
  • 224
  • I think this has already been answered here [Getting value of select (dropdown) before change][1] [1]: http://stackoverflow.com/questions/4076770/getting-value-of-select-dropdown-before-change – beenhere4hours Jul 05 '14 at 03:52

3 Answers3

3

You have to store the previous value yourself:

// store initial value
var initialValue = $('.cmbType').val();
$('.cmbType').data('previousValue', initialValue);

// change handler
$('.cmbType').change(function(e) {

    var previousValue = $(this).data('previousValue');

    // make decision
    alert(previousValue);

    // store previousValue
    $(this).data('previousValue', $(this).val());
});
strictlyk3v
  • 414
  • 4
  • 6
0

Try some thing like this:

<select id='cmbType'>
    <option value='1' >1</option>
    <option value='2' >2</option>
    <option value='3' >3</option>
</select>

javascript:

var preSelected = -1;
$(function(){
    $('#cmbType').bind('click change', function(e){
        if(e.type == 'change'){
            // change value detect
            alert(preSelected);
        }
        else{
            // click
            preSelected = $(this).val();
        }
    });
});
Ringo
  • 3,436
  • 2
  • 20
  • 36
  • What if user, focused to that input by pressing `tab` button ? then click event won't be triggered. – santosh Jul 25 '20 at 07:39
-2

You can use: .defaultValue Will give you the value.

  • This is wrong, the object . **defaultValue** property gives you the value set in the HTML code. See [link](http://help.dottoro.com/ljnqsrfe.php) – Viktor Mar 24 '21 at 20:07