reshad reshad - 6 months ago 22
Javascript Question

Track previous value of multiple select option

I have these three

select
's, I want to save all previous selected options, using
each
, I've done it for one of them but is there any way to do so without using same code for each of them? using
each
, for example.

jsFiddle



$(function() {
var previous;

$('#dropdown1').focus(function(e) {
previous = $(this).val();
});

$('#dropdown1').change(function(e) {
alert("previous value = " + previous + ", current value = " + $(this).val());
previous = $(this).val();
});
});

<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<select id="dropdown1">
<option>10</option>
<option>20</option>
<option>30</option>
</select>

<select id="dropdown2">
<option>40</option>
<option>50</option>
<option>60</option>
</select>

<select id="dropdown3">
<option>70</option>
<option>80</option>
<option>90</option>
</select>




Answer

Use array to maintain previous value for each select. and modify change and focus to target all select element and refer/modify their respective previous value from array:

var previous=[];
var selectelements = $('select');
$('select').focus(function(e){
   previous[$('select').index(this)] = $(this).val(); 
});

$('select').change(function(e){
    alert("previous value = " + previous[$('select').index(this)] + ", current value = " + $(this).val());
    previous[$('select').index(this)] = $(this).val();
});

Working Demo

Comments