user3748197
user3748197

Reputation: 33

Get a old value of input before change and change total value to + or -

I want to make points distribution form. I got 4 inputs type number value 0-100 and total = 100 points. So we can put 25 points in each input. I already get it work to validate inputs number min 0 max 100 and it subtracts from total changed input value. I have a problem with adding to Total. If user change already changed value I need to make Total + value(before change) and then Total - value(after change). I don't know how to get value before change.

My html

<input type="number" min="0" max="100" name="1" />
<input type="number" min="0" max="100" name="2" />
<input type="number" min="0" max="100" name="3" />
<input type="number" min="0" max="100" name="4" />
<input type="text" id="Total" name="Total" value="100"/>

My script

$("input[type=number]").keyup(function(event) {
    max=100;
  min=0;
    value=( parseInt($(this).val()));
    if(value < min || isNaN(parseInt(value))) 
        $(this).val(0)
    else if(value > max) 
        $(this).val(100);
    else return value;
});

var total, myVal;
$("input[type=number]").change(function(event) {
    maxPoints = parseInt($('#Total').val());
    myVal = ( parseInt($(this).val()) || 0);
    total = maxPoints - myVal;
    $('#Total').val(total);
});

If i would be able to save old value to some var i would change .onchange script to something like this and i think it should work. But how i can get old value ?

$("input[type=number]").change(function(event) {    
    oldValue = ???? - how to get this ? :P
    if(oldValue>0){
        maxPoints = parseInt($('#Total').val()) + oldValue;
    }else{
        maxPoints = parseInt($('#Total').val());
    }    
    myVal = ( parseInt($(this).val()) || 0);
    total = maxPoints - myVal;
    $('#Total').val(total);
});

There is js fiddle how it works now. Fiddle here

Upvotes: 2

Views: 5106

Answers (1)

Amit Wagner
Amit Wagner

Reputation: 3264

Hi just save the old value like this

$("input[type=number]").change(function(event) {    
    oldValue = $(this).data('oldvalue');
    if(oldValue>0){
        maxPoints = parseInt($('#Total').val()) + oldValue;
    }else{
        maxPoints = parseInt($('#Total').val());
    }    
    myVal = ( parseInt($(this).val()) || 0);
    total = maxPoints - myVal;
    $(this).data('oldvalue',$(this).val()) // update old value to new value
    $('#Total').val(total);
});
<input type="number" min="0" data-oldvalue='0' max="100" name="1" />
<input type="number" min="0" data-oldvalue='0' max="100" name="2" />
<input type="number" min="0" data-oldvalue='0' max="100" name="3" />
<input type="number" min="0" data-oldvalue='0' max="100" name="4" />
<input type="text" id="Total" name="Total" value="100"/>

Upvotes: 2

Related Questions