yesman
yesman

Reputation: 7829

jQuery - how do you select the previous chosen Select option?

Given this select element:

<select id="foo"> 
<option value="1">1</option>
<option value="2">3</option>
<option value="3">3</option>
</select>

And I select the option 1 first, how do I retrieve the value of 1 after I choose 2 in this select dropdown using jQuery?

Upvotes: 1

Views: 1459

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

Just save the previous selection, stored it in a variable or as an attribute on the select itself (attributes are my preference as you can see them in the DOM inspector), example below:

$('#foo').change(function(){

    // Get previous value (if any)
    var lastValue = $(this).attr("data-lastvalue"); // or $(this).data("lastvalue"); 

    // Do stuff

    // Save new value
    $(this).attr("data-lastvalue", $(this).val());
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/5kznycjn/2/

Upvotes: 1

Related Questions