-2

Having read for hours on the web and tried various things I am lost as to the answer to my problem. I want to be able to check a checkbox and get the value from an input box. ie If more than 1 checkbox is checked the values (both £100) would produce a sum of £200. I am getting "100100"!

My html table is produced with PHP with value '$price' from a mySQL database as a DECIMAL (10,2):

<html>
<table>
<tr>
<td><input name='payInvoice' type='checkbox' onchange='add()'></td>
<td><input id='amountToPay' value=$price></td>
</tr>
</table>
</html>

and javascript:

<script>
function add(){
var payOff = " "
    document.getElementById('poff').value = "";   
var payoff = document.getElementsByName("payInvoice");
    for (var i=0; i<payoff.length; i++){
    if (payoff[i].checked == true){
    amount = document.getElementById("amountToPay");
    $s = parseInt(amount.value);
    payOff += ($s) ;   
    document.getElementById('poff').value = payOff;
        } 
    }
 }
</script>
Beepee
  • 11
  • 2
  • 1
    Does this answer your question? [How to force addition instead of concatenation in javascript](https://stackoverflow.com/questions/13953939/how-to-force-addition-instead-of-concatenation-in-javascript) – CBroe May 28 '20 at 08:02
  • Seems that payOff is being treated as a string – N Scholefield May 28 '20 at 08:06

1 Answers1

1

Change var payOff = " " to var payOff = 0 and it will work.You are adding string to integers hence its not working.

So when you write payOff += $(s); you are actually doing payOff = (" " + interger) which is basically string concatenation hence you will always get a string back

Shijil Narayanan
  • 1,011
  • 8
  • 21