Adding checkbox values together - works but got small problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sodkgb
    New Member
    • Apr 2008
    • 1

    Adding checkbox values together - works but got small problem

    This is my first time posting to the forum and welcome assistance to fix this javascript:

    [HTML]<script language="JavaS cript">
    <!--
    function calculate(what) {
    what.answer.val ue =0;
    for (var i=1,answer=0;i< 6;i++)
    answer += (what.elements['CourseOrder' + i].checked)&(what .elements['CourseOrder' + i].value-0);
    what.answer.val ue = answer;
    }
    //-->
    </script>

    <form>
    <INPUT type="checkbox" NAME="CourseOrd er1" VALUE="1" onclick="calcul ate(this.form)" ><br>
    <INPUT type="checkbox" NAME="CourseOrd er2" VALUE="1" onclick="calcul ate(this.form)" ><br>
    <INPUT type="checkbox" NAME="CourseOrd er3" VALUE="1" onclick="calcul ate(this.form)" ><br>
    <INPUT type="checkbox" NAME="CourseOrd er4" VALUE="1" onclick="calcul ate(this.form)" ><br>
    <INPUT type="checkbox" NAME="CourseOrd er5" VALUE="5" onclick="calcul ate(this.form)" ><br>

    <input type="text" name="answer">

    </form>[/HTML]

    I want to change the values, but when the values are changed it does not work or even provide the correct value. It is treating is checkbox as 1 and doesn't see the value of the checkbox?

    Any help welcome,

    Kevin
    Last edited by gits; Apr 4 '08, 01:36 PM. Reason: added code tags
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Replace what with document.forms[0] everywhere in the function.
    And don't pass any argument to the function calculate()


    Regards

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      The problem is caused by the shorthand notation "&". Try this instead:
      [code=javascript]if (what.elements['CourseOrder' + i].checked)
      answer += parseInt(what.e lements['CourseOrder' + i].value);[/code]

      Comment

      Working...