Draineh Draineh - 6 months ago 22
jQuery Question

Select - get previous and new value only on change

I have a page with a few select boxes on, my objective is to capture the previous value and the new value which I've managed to achieve in the code below.
This builds up a one to one pairing of arrays so array position 0 for previous should be the previous value for the new value in array position 0 of updates. There is server side processing to validate the data passed back so this part doesn't worry me too much.

The problem is - if a user clicks on the select box the focus event is thrown, I capture the previous value, if the user then decides to stay on the same value they just click back on it and the change event is not thrown which puts my array out of sync and leaves me with a false previous value (if it doesn't change I don't need to capture it as previous).

Have I overcomplicated? Any suggestions or points around better handling the user selecting the same value would be appreciated.

var updates = [];
var previous = [];

$("select").on('focus', function () {
item = {};
item["id"] = this.value;
item["name"] = $(this).find('option:selected').text();
previous.push(item);

}).change(function() {
item = {};
item["id"] = this.value;
item["name"] = $(this).find('option:selected').text();
updates.push(item);
});


Thanks to the pointer from the answer below I've ended up with the following code;

Final working code



var updates = [];

$("select").on('focus', function () {
item = {};
item["id"] = this.value;
item["name"] = $(this).find('option:selected').text();
updates.push(item);

}).change(function() {
if (updates.length > 1) {
updates = updates.slice(updates.length-1,updates.length);
}
previousPos = updates.length-1;
newItem = {};
updates[previousPos]["newid"] = this.value;
updates[previousPos]["newname"] = $(this).find('option:selected').text();
$(this).blur();

$.ajax({
type: 'POST',
url: '/update',
data: JSON.stringify(updates)
});
});


I'm handling CSRF token setup elsewhere with ajaxSetup.

Answer

why don't you just push to one array instead of two. This way you can get the array length/count to determine if there was a previously selected option?

if(item.length >= 2 ){
// do something
}