JeremyS
JeremyS

Reputation: 329

Selecting a new value in a dropdown list while remembering the old value in Jquery

I'm working on a webshop where customers can choose an amount of items to purchase via a drop down list. Each item have a point value and I calculate the total of their purchase via jQuery (onChange event):

function showPoints(itemPointValue, ddlAmount){
    var customerPoints = parseInt($('p#points').html());
    currentPoints = customerPoints - (ddlAmount * itemPointValue);
    $('p#points').html(currentPoints);
}//showPoints     

The only problem here is if they change their amount from say 5 to 4, another 4 * the point value gets taken off their "total points". Their total points ends up becoming totally inaccurate and they can even go below 0. I thought of using jquery.data to set an "oldValue" variable but IE does not support this. Any suggestions?

Upvotes: 0

Views: 646

Answers (4)

JeremyS
JeremyS

Reputation: 329

I solved this issue by using two events on my drop down lists. onClick to save the old data using jquery.data and onChange to check the old value against the new value. If the new value is smaller then the old value I adjust the point total accordingly.

HTML:

<select name="dropdown onClick="saveOld(this.value, this.name)" onchange="showPoints(points, this.value,this.name)">

JS/Jquery

function showPoints(pointCategory, ddlAmount, name){
    old = jQuery.data(document.body,name);
    var Points = parseInt($('p#points').html());
    if(old > ddlAmount){
       diff =  old - ddlAmount;
       currentPoints = Points + (diff * pointCategory);
    }else{
       currentPoints = Points - (ddlAmount * pointCategory);
    }
    $('p#points').html(currentPoints);
}//showPoints

function saveOld(oldAmount, name){
    $(document.body).data(name,oldAmount);
}//saveOld

Thank you all for your answers!

Upvotes: 0

Alex Bularca
Alex Bularca

Reputation: 21

You could store the previous value on a custom attribute as stated above, and you could use the focus event to set the old value, something in the lines of this should work:

$('p#points').on('focus', function () {
    $(this).attr('old-value', $(this).val();
});

Upvotes: 2

djakapm
djakapm

Reputation: 175

How about, creating custom attribute on the element:

$('p#points').attr('old-value',5);

and retrieve it like this:

$('p#points').attr('old-value');

Upvotes: 0

jcolicchio
jcolicchio

Reputation: 808

Why not just recalculate the total point cost any time any dropdown is changed, and re-calculate currentPoints by subtracting the new total from customerPoints? This, to me, seems like a much cleaner solution than adding and subtracting values

Upvotes: 0

Related Questions