Search code examples
javascriptjqueryeventskeyup

JQUERY ; 2 value in keyupevents


I am curious how do i get the individual values of #item- + i and #value + i because i cannot use $(this).val() for both of them.

var count = 10;
for (var i=0; i<count; i++){
$('#item-' + i,'#value' + i).on("keypress keyup", function() {
console.log("item changed" + $(this).val());
console.log("value changed" + $(this).val());                                 
});
}

Initially, I do it this way, because i want value and item to be a global variable. may i ask if there is any other way to do so? i would like to calculate the items together. e.g. value + item into total_value, but it's output is always 0 as it cannot read inside my function.

var i = 0;
var item = 0;
var value = 0;
var total_value = 0;
while (i <= count){
$('#item-' + i).on("keypress keyup", function() {
item = $(this).val();                                  
});
$('#value-' + i).on("keypress keyup", function() {
value = $(this).val();
});
i++;
}
total_value = item + value;

due to the differences in class e.g my items has #item-1, #item-2.... and so on,, #value-1, #value-2.... and so on,

i can't seem to use the following example

$('#qty, #price').on('keyup keypress',function() {
    var qty = parseInt($('#qty').val());
    var price = parseFloat($('#price').val());
    $('#total').val((qty * price ? qty * price : 0).toFixed(2));
});

Solution

  • Copy i into the function as i cannot get into the function.