Search code examples
javascriptfunctionvariablesiterationonkeyup

is it possible to assign id name to a variable and use it in a function in javascript


I am creating an html form that will take quantity values in input for items and calculate the individual total cost and show it adjacent to each input box and show the grand total at the bottom of the form. I am doing it with JS and KeyUp function and trying to iterate the function.

My HTML

<p><span>T-Shirts </span> <input type="number" name ="tshirts" value="0" id="tshirts">&nbsp;&nbsp;<span class="tshirtscost">0</span><br></p>
<p><span>Shirts </span> <input type="number" name ="shirts" value="0" id="shirts">&nbsp;&nbsp;<span class="shirtscost">0</span><br></p>
<p><span>Kurtas </span> <input type="number" name ="kurtas" value="0" id="kurtas">&nbsp;&nbsp;<span class="kurtascost">0</span><br></p>

<div id="totalcost"></div>

My JS

var item = ["T-Shirt/s","Shirt/s","Kurta/s"];
var itemcost=100;
var text = "";
var i;

for (i = 0; i < item.length; i++) {
 text = item[i].replace(/ |-|&|\//g, '').toLowerCase();

 itemid="#" + text;
 itemclass="." + text + "cost";

 $(itemid).keyup(function(){
    var x = $(itemid).val();
    $(itemclass).css("background-color", "pink").html("Rs."+ (x * itemcost));
    totalcost();

});

function totalcost(){
var tot=$('#tshirts').val()*itemcost + $('#shirts').val()*itemcost + $('#kurtas').val();
    $("#totalcost").css("background-color", "pink").html("<span style='font-weight:700'>Total Cost : </span>Rs."+tot);
  }
}

The idea to iterate the js operation is because I have lot many more items for input and calculation in the form.

However, I am not sure trying to create a variable with a class name and using it in the function is a possibility. But if something similar can be done, it will save me writing lots of lines of code for each item.

This code is not working. Probably for obvious reasons that I cant see. Any help will be greatly appreciated.


Solution

  • You need to use inner function because of this.

    In you example, you're updating two variables in the loop - itemid and itemclass. But every function you're registering in .keyup will remember not the values for these variables, but the variable itself. And since after the last loop these variables will contain the last value, all callbacks will use the last value of itemid and itemclass. That's why you need to use inner function, so inner function will have id and cls variables created each time with the correct value. What are're looking is probably this:

    $(itemid).keyup((function (id, cls) {
        return function () {
            var x = $(id).val();
            $(cls).css("background-color", "pink").html("Rs." + (x * itemcost));
            totalcost();
        }
    }(itemid, itemclass)));
    

    I've created a plunker to show that.