i have page few select boxes on, objective capture previous value , new value i've managed achieve in code below. builds 1 one pairing of arrays array position 0 previous should previous value new value in array position 0 of updates. there server side processing validate data passed part doesn't worry me much.
the problem - if user clicks on select box focus event thrown, capture previous value, if user decides stay on same value click on , change event not thrown puts array out of sync , leaves me false previous value (if doesn't change don't need capture previous).
have overcomplicated? suggestions or points around better handling user selecting same value 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 pointer answer below i've ended 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 ajaxsetup.
why don't push 1 array instead of two. way can array length/count determine if there selected option?
if(item.length >= 2 ){ // }