Need help with Javascript radio buttons (values)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • norbit
    New Member
    • Feb 2008
    • 3

    Need help with Javascript radio buttons (values)

    Hello,

    I’m new to learning JavaScript. I was trying out a simple script but I can’t

    seem to make it work:

    [HTML]<HTML><HEAD><TI TLE>Radio Buttons</TITLE>
    <SCRIPT language=JavaSc ript>

    function process()
    {
    1 for (i = 0; i < document.form1. Q1.length; i++)
    2 {if (document.form1 .Q1[i].checked == true)
    3 {Num1 = document.form1. Q1[i].value;}
    4 }
    5
    6 for (i=0; i < document.form1. Q2.length; i++)
    7 {if(document.fo rm1.Q2[i].checked == true)
    8 {Num2 = document.form1. Q2[i].value;}
    9 }
    10
    11 document.write( "The sum is " + parseInt(Num1) + parseInt12(Num2 ));
    13}
    14</SCRIPT>

    <BODY>
    <FORM name=form1>
    <H4>First Set</H4>

    <INPUT type=radio value=2 name=Q1>2<BR>
    <INPUT type=radio value=1 name=Q1>1<BR>
    <INPUT type=radio value=-1 name=Q1>-1<BR>
    <INPUT type=radio value=-2 name=Q1>-2<BR>

    <H4>Second Set</H4>

    <INPUT type=radio value=2 name=Q2>2<BR>
    <INPUT type=radio value=1 name=Q2>1<BR>
    <INPUT type=radio value=-1 name=Q2>-1<BR>
    <INPUT type=radio value=-2 name=Q2>-2<BR>
    <BR>
    <INPUT onclick=process () type=button value=Add>
    <BR></FORM></BODY></HTML>[/HTML]

    The result should come out as the arithmetic addition of the values of the

    radio buttons, right? But its giving me the result of concatenation operation.

    Am I missing a code/command? Thanks for the help
    Last edited by gits; Feb 28 '08, 12:38 PM. Reason: added code tags
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Next time you better enclose any code within the appropriate code tags! See the Posting Guidelines.

    The writeln does no addition, it just echoes strings. Calculate the total and write that, e.g.[html]var total=parseInt( Num1)+parseInt( Num2);[/html]Then write 'total' to the screen.

    Ronald

    Comment

    • norbit
      New Member
      • Feb 2008
      • 3

      #3
      Sorry about the messy first post, Ronald...
      And thanks for the helpful reply, it worked..

      I also found out that this can also work:

      [CODE=javascript]document.write( "The sum is " + (parseInt(Num1) + parseInt(Num2)) );
      [/CODE]
      thank again :)
      Last edited by gits; Feb 28 '08, 12:39 PM. Reason: added code tags again

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        You are welcome. See you next time.

        Ronald

        Comment

        Working...