convert a string to a number, do math on it, then convert it back and give the span that value as a string

StackOverflow https://stackoverflow.com/questions/20461267

Pregunta

i am trying to take entered values from textboxes and convert them to strings, total the amount, and then set the innerHTML of a <span> to that value.

function addBills(){
    var 
        hundreds = parseInt($("#input100").innerHTML(),10)*100;
        fifties = parseInt($("#input50").innerHTML(),10)*50;
        twenties = parseInt($("#input20").innerHTML(),10)*20;
        tens = parseInt($("#input10").innerHTML(),10)*10;
        fives = parseInt($("#input5").innerHTML(),10)*5;
        ones = parseInt($("#input1").innerHTML(),10);
        regTotal = hundreds+fifties+twenties+tens+fives+ones;
    window.alert(regTotal);
    /*var regTotal = (($("#input100").innerHTML * 100)+($("#input50").innerHTML * 50)+($("#input20").innerHTML * 20)+($("#input10").innerHTML * 10)+($("#input5").innerHTML *5)+($("#input1").innerHTML));*/
    for(var counter = 0;counter<regTotal;counter++){
        regString = regTotal.toString();
        $("#totalCount").innerHTML("regTotal");
    }
};
¿Fue útil?

Solución

You're Doing It Wrong

For starters.

function addBills(){
    var 
        hundreds = parseInt($("#input100").innerHTML(),10)*100;

hundreds is the only local var. All others are global. Fix: use comma's instead of semicolons to separate variables in one var-statement.

Secondly inputfields have a value (not innerHTML, and especially not innerHTML() as a function).
inputfields values are always text. One can convert them to numbers by either Number(string) or parseInt(string, radix/base) (or adding a + in front of the string).

Finally, once you have the span-element you thus simply do: elm_span.innerHTML=yourNumber; and bob's your uncle!

EDIT:
Your current loop makes no sense.. I mean, if regTotal is the total of the cash... and you have one span with the unique id totalCount... it's completely pointless (just as trying to convert the totalCount to string a couple of thousands of times)

You probably want something like:

function addBills(){
   var hundreds = Number(document.getElementById('input100').value)*100
   ,   fifties = Number(document.getElementById('input50').value)*50
   ,   twenties = Number(document.getElementById('input20').value)*20
   ,   tens = Number(document.getElementById('input10').value)*10
   ,   fives = Number(document.getElementById('input5').value)*5
   ,   ones = Number(document.getElementById('input1').value)
   ,   regTotal = hundreds+fifties+twenties+tens+fives+ones
   ; //end local
   document.getElementById('totalCount').innerHTML=regTotal;
}

Working example fiddle here

Hope this helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top