javascript - Checkbox Calculations Not Working -


hey guys have question calculating checkboxes , total in real time here code:

function calc()   {     thetotal = 0;     checkform = document.formname;     (i=0; <= checkform.length-1; i++) {         if (checkform.elements[i].type == "checkbox") {             if (checkform.elements[i].checked == true) {                 document.getelementbyid("total").value = thetotal;             }         }     }     document.getelementbyid("total").innerhtml = thetotal; } 

here html code:

<p>total: $<span id="total">0</span></p>      <tr>     <td> <br> <center> <img src="shirt1.jpg" width="160" height="150" alt="shirt1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">obey t-shirt: $19.99</label> </center> </br></td>     <td> <br> <center> <img src="shoe1.jpg" width="160" height="150" alt="shoe1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">shoe - red lace: $19.99</label> </center> </br> </td>     <td> <br> <center> <img src="snapback1.jpg" width="160" height="150" alt="snap1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">snapback bullets: $19.99</label> </center> </br> </td> </tr> 

when click on 1 of selected checkboxes won't give me calculation want. able me one?

there lot of problems seems in code. here writing simpler you.

you don't need iterate on every form element, when calling separately each checkbox.

you need make thetotal global variable having total of checked items. right resetting 0 on every function call.

you can try this

var thetotal = parsefloat(0);  function calc(control) {     if (control.checked == true) {         thetotal += parsefloat(control.value);     } else {         thetotal -= parsefloat(control.value);     }     document.getelementbyid("total").innerhtml = thetotal; } 

and call this

<input type="checkbox" onchange="calc(this)" value="19.99"> 

js fiddle demo


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -