calculation function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • azura
    New Member
    • Jul 2008
    • 47

    calculation function

    dear sir..my friend give me one code how to calculate without pressing any button... but i didn't know how to insert function to make it work... very very newbie in calculation using javascript..ple ase someonehelp me please..
    Code:
    var total = (document.getElementById("cam").value + document.getElementById("final_exam").value) / 2;
    
    document.getElementById("total").value = total;
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Hello Azura. There are many ways u can do that without clicking a button. can u please send me the full code what u are working at. If your form contains three text box means, 1 for entering the first value, 2 for entering the second value and the 3 for total. in the 2nd text box you write the event onblur="calcula te()". And your code in calculate function. That will match ur requirement. if any doubts post back it I will help u out.

    [HTML]<html>
    <head>
    <script type="text/javascript">
    function calculate()
    {
    var total = (parseInt(docum ent.getElementB yId("cam").valu e) + parseInt(docume nt.getElementBy Id("final_exam" ).value)) / 2;
    document.getEle mentById("total ").value = total;
    }
    </script>
    </head>
    <body>
    Enter a <input type="text" id="cam"><br/>
    Enter b <input type="text" id="final_exam " onblur="calcula te()"><br/>
    Total = <input type="text" id="total"><br/>
    </body>
    </html>[/HTML]

    In the function I used parseInt() for getting the data. In javascript whatever the data got from input item will be defaultly consider as a String. Inorder to convert I had used it

    Regards
    Ramanan Kalirajan
    Last edited by RamananKalirajan; Aug 27 '08, 04:12 AM. Reason: Added the Codes

    Comment

    • azura
      New Member
      • Jul 2008
      • 47

      #3
      thanks.... it's work but i change it into onclick at the final score... thanks again sir...

      Comment

      • azura
        New Member
        • Jul 2008
        • 47

        #4
        dear sir... it work when i data only..how can i get those work in many data... like repeat region??

        Comment

        • RamananKalirajan
          Contributor
          • Mar 2008
          • 608

          #5
          Originally posted by azura
          dear sir... it work when i data only..how can i get those work in many data... like repeat region??

          Hello I am really sorry I am not able to follow ur requirement clearly. can u please post me the code what u are working on. U want to calculate for many texts. [Kind Note: pls dont call me as sir, call me Ramanan. just few months back i completed my college]

          Regards
          Ramanan Kalirajan

          Comment

          • azura
            New Member
            • Jul 2008
            • 47

            #6
            ok i take all the information is from my database..so admin just key in the number and total will came auto..but it work if one data that i retrieve from database..but if there is many info in my database how??

            [PHP]<html>
            <head>
            <title>List Registered Subject | Medic Assessment System</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            <meta name="keywords" content="Keywor ds here">
            <meta name="descripti on" content="Descri ption here">
            <meta name="Author" content="Joseph De Araujo">
            <meta name="Publisher " content="MyFree Templates.com">
            <meta name="robots" content="index, follow"> <!-- (robot commands: all, none, index, no index, follow, no follow) -->
            <meta name="revisit-after" content="30 days">
            <meta name="distribut ion" content="global ">
            <meta name="rating" content="genera l">
            <meta name="content-language" content="englis h">
            <title>Class List View | Medic Assessment System</title>
            <script language="JavaS cript" type="text/JavaScript" src="images/myfreetemplates .js"></script>

            <style type="text/css">
            <!--
            .basestyle {
            color: #FFFFFF;
            font-size: 10px;
            font-family: Verdana, Arial, Helvetica, sans-serif;
            }
            h1 {
            font-size: 16px;
            font-weight: bold;
            font-family: Verdana, Arial, Helvetica, sans-serif;
            }
            body, td, p, input {
            font-size: 11px;
            font-family: Verdana, Arial, Helvetica, sans-serif;
            color: #333333;
            }
            .navlinks {
            font-size: 14px;
            font-family: Arial, Helvetica, sans-serif;
            font-weight: bold;
            color: #FFFFFF;
            }
            .style6 {
            font-size: 12px;
            color: #000000;
            font-weight: bold;
            }
            .style7 {
            font-size: 12px;
            font-weight: bold;
            }
            .style10 {color: #000000}
            a:link {
            text-decoration: none;
            }
            a:visited {
            text-decoration: none;
            }
            a:hover {
            text-decoration: none;
            }
            a:active {
            text-decoration: none;
            }
            .style11 {color: #000000; font-size: 12px;}
            .style12 {font-weight: bold}
            .style13 {
            font-size: 12px;
            color: #000000;
            background-color: #D6D6D6;
            height: 22px;
            width: 72px;
            outline: 1;
            border: 1;
            font-weight: normal;
            }
            .style15 {font-size: 11px; font-family: Verdana, Arial, Helvetica, sans-serif; }
            -->
            </style>

            <script type="text/javascript">

            function calculate()

            {

            var total = (parseInt(docum ent.getElementB yId("cam").valu e) + parseInt(docume nt.getElementBy Id("final_exam" ).value)) / 2;

            document.getEle mentById("total ").value = total;

            }

            </script>
            <script type="text/javascript">

            function calculate()

            {

            var total = (parseInt(docum ent.getElementB yId("cam").valu e) + parseInt(docume nt.getElementBy Id("final_exam" ).value)) / 2;

            document.getEle mentById("total ").value = total;

            }

            </script>

            <script src="../../../Scripts/AC_RunActiveCon tent.js" type="text/javascript"></script>
            </head>
            <body style="margin:0 ; background-color: #E4E7E6;" <?php if($saved){echo 'onload="alert( \'Records successfully saved.\');"';}? >>

            <table width=1097 height="100%" border=1 align="center" cellpadding=0 cellspacing=0>

            <tr align="center" valign="middle" >
            <td height="34" colspan="2" class="style11" >You are here&gt;&gt;<a href="main.php" >Main Menu</a> &gt;&gt;Examina tion&gt;&gt;Ins ert Result </td>
            </tr>
            <tr>
            <td width="202" height = "90%"valign="to p"><div align="center" class="style6">

            </div>
            <div align="center" class="style7"> EXAMINATION</div>
            <ul>
            <li><span>
            <a href="exm.php"> Insert Result
            </a></span> </li>
            </ul>
            <p><span class="style7"> <a href="<?php echo $logoutAction ?>">&gt;&gt;LOG OUT</a></span> </p>
            <p align="center" class="style7"> Date: <?php echo date('d-m-Y') ."\n";?></p></td>
            <td width="889" valign="top" style="padding-left:20px; padding-top:25px; padding-right:40px; padding-bottom:35px; "><p>
            <form id="form2" name="form2" method="post" action="">
            <p align="center" class="style12 style28 style29"><stron g>LIST REGISTERED SUBJECTS</strong></p>
            <p align="center" class="style12" >&nbsp;</p>
            <blockquote>
            <blockquote>
            <blockquote>
            <blockquote>
            <p>&nbsp;</p>
            <table width="601" height="138" border="0">


            <tr>
            <td height="26">Ses sion</td>
            <td><div align="center"> :</div></td>
            <td><input name="sessi" type="text" id="sessi" value="<?php echo $row_test['sessi']; ?>" size="10" readonly="true" /></td>
            </tr>
            <tr>
            <td height="26">Yea r</td>
            <td><div align="center"> :</div></td>
            <td><input name="year" type="text" id="year" value="<?php echo $row_test['year']; ?>" size="10" readonly="true" /></td>
            </tr>
            <tr>
            <td width="92" height="26"><di v align="left">Gr oup</div></td>
            <td width="10"><div align="center"> :</div></td>
            <td width="360"><in put name="group" type="text" id="group" value="<?php echo $row_test['group']; ?>" size="10" readonly="true" /></td>
            </tr>
            <tr>
            <td height="22">Sub ject Code</td>
            <td><div align="center"> :</div></td>
            <td><input name="s_code" type="text" id="s_code" value="<?php echo $row_test['s_code']; ?>" size="10" readonly="true" /></td>
            </tr>
            <tr>
            <td height="23">Tit le</td>
            <td><div align="center"> :</div></td>
            <td><input name="s_title" type="text" id="s_title" size="80" value="<?php echo $row_Recordset2['s_title']; ?>" readonly="true" /></td>
            </tr>
            </table>
            </blockquote>
            </blockquote>
            </blockquote>
            </blockquote>

            <p>&nbsp;</p>
            <table width="609" height="54" border="0" align="center">
            <tr>
            <td width="60" height="28" scope="col"><sp an class="style15" >Matric No.</span></td>
            <td width="48" scope="col"><sp an class="style15" >CAM</span></td>
            <td width="48" scope="col"><di v align="left" class="style15" >
            <div align="center"> Final Exam</div>
            </div> </td>
            <td width="48" scope="col"><di v align="left" class="style15" >
            <div align="center"> Total Score</div>
            </div></td>
            <td width="383" scope="col"><sp an class="style15" >Grade</span></td>
            </tr>

            <?php do { ?>
            <tr>
            <td height="20" scope="col"><in put name="matric_no[]" type="text" id="matric_no[]" value="<?php echo $row_test['matric_no']; ?>" size="10" readonly="true" /></td>
            <td scope="col"><in put name="cam" type="int" id="cam" size="8" /></td>
            <td scope="col" ><input name="final_exa m" type="int" id="final_exam " size="8" onClick="calcul ate()" /></td>
            <td scope="col"><in put name="total" type="int" id="total" size="8" readonly="true" /></td>
            <td scope="col"><in put name="grade" type="text" id="grade" size="8" onClick="grade( )"/></td>
            </tr>
            <?php } while ($row_test = mysql_fetch_ass oc($test)); ?>
            </table>
            <p align="center"> &nbsp;</p>
            <table width="200" border="0" align="center">
            <tr>
            <th scope="col"><in put name="save" type="submit" class="style13" id="save" value="Save" /></th>
            <th scope="col"><sc ript type="text/javascript">
            AC_FL_RunConten t( 'codebase','htt p://download.macrom edia.com/pub/shockwave/cabs/flash/swflash.cab#ver sion=5,0,0,0',' width','77','he ight','22','src ','exmtry','qua lity','high','p luginspage','ht tp://www.adobe.com/shockwave/download/download.cgi?P1 _Prod_Version=S hockwaveFlash', 'bgcolor','#E4E 7E6','scale','n oborder','movie ','exmtry' ); //end AC code
            </script>
            <noscript>
            <object classid="clsid: D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macrom edia.com/pub/shockwave/cabs/flash/swflash.cab#ver sion=5,0,0,0" width="77" height="22">
            <param name="movie" value="exmtry.s wf">
            <param name="quality" value="high">
            <param name="bgcolor" value="#E4E7E6" >
            <param name="SCALE" value="noborder ">
            <embed src="exmtry.swf " width="77" height="22" quality="high" pluginspage="ht tp://www.adobe.com/shockwave/download/download.cgi?P1 _Prod_Version=S hockwaveFlash" type="applicati on/x-shockwave-flash" bgcolor="#E4E7E 6" scale="noborder "></embed>
            </object>
            </noscript></th>
            </tr>
            </table>
            <div align="center"> </div>
            <p align="center"> &nbsp; </p>
            <p>&nbsp;</p>
            <p align="center" class="style8"> &nbsp;</p>
            </form> </td>
            </tr>

            <tr>
            <td height="58" colspan="2"><ta ble width="100%" height="39" border="0" cellpadding="0" cellspacing="0" >
            <tr>

            <td align="center" class="basestyl e"><span class="style31 style10">&copy; Copyright . All Rights Reserved.&nbsp; <a href="http://www.myfreetempl ates.com" class="basestyl e"></a></span></td>
            </tr>
            </table></td>
            </tr>
            </table>
            </body>

            <?php

            mysql_free_resu lt($test);

            ?>
            </html>[/PHP]

            Comment

            • RamananKalirajan
              Contributor
              • Mar 2008
              • 608

              #7
              I am not good at PHP. But for your question i.e. adding many values retrieved from the db, wether you display all the value in a table inside a textbox that should be added.

              For ex. u are having three values in the DB. u want the reult of the three values added and u are showing all the values in the table like

              tr td input --> first data
              tr td input --> second data
              tr td input --> third data
              tr td input --> total value

              Like this. please correct If i am wrong anywhere. if this is ur requirement u can easily sum all the values. For each and every input u will be giveing some Id's. set the Id sequentially starting from 0,1 and so on. In the calculate()

              [HTML]var i=0;
              var totall=0
              var x;
              while(true)
              {
              x=parseInt(docu ment.getElement ById(i).value);
              if(x==null||x== undefined)
              break;
              else
              total+=x;
              }
              document.getEle mentById('total ').value=total;[/HTML]

              If u doesn't need this. pls post me wat u need. Sorry I am not good in PHP

              Regards
              Ramanan Kalirajan

              Comment

              • azura
                New Member
                • Jul 2008
                • 47

                #8
                you gave if we calculate one data,right?? what if we want to calculate many data like. the earlier part you gave it's work but if there is one data only..

                cam(insert number) + final(insert number) = total (auto)(1 data)

                cam (insert number) + final(insert number) = total (auto)(2 data)

                Comment

                • acoder
                  Recognized Expert MVP
                  • Nov 2006
                  • 16032

                  #9
                  You can use document.getEle mentsByName("ca m") and "final_exam " to get a list of input elements. Then loop over them using a for loop, e.g.
                  [code=javascript]for (i = 0; i < cam.length; i++) {
                  //cam[i] contains the i'th element...
                  [/code]

                  Comment

                  • azura
                    New Member
                    • Jul 2008
                    • 47

                    #10
                    Code:
                    <script type="text/javascript">
                    
                    function calculate()
                    {
                    for (i = 0; i < cam.length; i++) {
                    
                    var total = (parseInt(document.getElementByName("cam").value) + parseInt(document.getElementByName("final_exam").value));
                    
                    document.getElementByName("total").value = total;
                    
                    }
                    }
                    </script>
                    like this??? i had tried but don't have any data came out... gosh!! very stuck!!

                    Comment

                    • acoder
                      Recognized Expert MVP
                      • Nov 2006
                      • 16032

                      #11
                      No, document.getEle mentByName("cam ") returns an array of elements, so something like:
                      [code=javascript]var cams = document.getEle mentByName("cam ");
                      var finals = document.getEle mentByName("fin al_exam");
                      var total = 0;
                      for (i = 0; i < cams.length; i++) {
                      var total += parseInt(cams[i].value) + parseInt(finals[i].value);
                      }
                      document.getEle mentByName("tot al").value = total;[/code]

                      Comment

                      • azura
                        New Member
                        • Jul 2008
                        • 47

                        #12
                        Code:
                        <script type="text/javascript">
                        
                        function calculate()
                        
                              var cams = document.getElementByName("cam");
                          
                              var finals = document.getElementByName("final_exam");
                          
                              var total = 0;
                          
                              for (i = 0; i < cams.length; i++) {
                          
                                  var total = parseInt(cams[i].value) + parseInt(finals[i].value);
                          
                            }
                          
                              document.getElementByName("total").value = total;
                        
                        
                        
                        </script>
                        still don't work..

                        Comment

                        • Dormilich
                          Recognized Expert Expert
                          • Aug 2008
                          • 8694

                          #13
                          that's because of a typing error: it should be
                          Code:
                          document.getElement[b]s[/b]ByName()
                          // and
                          document.getElementsByName("total")[0].value = total;
                          like acoder said, getElementsByNa me is always returning an array (even if there's only one element present)

                          Comment

                          • azura
                            New Member
                            • Jul 2008
                            • 47

                            #14
                            Code:
                            <script type="text/javascript">
                             function calculate()
                             
                            
                            var cams = document.getElementsByName("cam");
                            
                             
                            
                                  var finals = document.getElementsByName("final_exam");
                            
                            
                                  var total = 0;
                            
                             
                            
                                  for (i = 0; i < cams.length; i++) {
                            
                             
                            
                                      var total = parseInt(cams[i].value) + parseInt(finals[i].value);
                            
                             
                            
                                }
                            
                             
                            
                               document.getElementsByName("total")[0].value = total;
                            
                             
                            }
                            if (total >100)
                            {
                            alert('Total cannot be more than 100.!!');
                            }
                            else if (total<0)
                            {
                            alert('Total cannot be negative.!!');
                            }
                            else
                            {
                            document.getElementById("total").value = total;
                            var grade;
                            
                            if (total>=80)
                            {
                            	grade = 'A';
                            }
                            
                            else if(total>=70)
                            {
                            	grade = 'B';
                            } 
                            else if(total>=60)
                            {
                            	grade = 'C';
                            }
                            else if(total>=50)
                            {
                            	grade = 'D';
                            }
                            else if(total>=40)
                            {
                            	grade = 'E';
                            } 
                            else
                            {
                            	grade = 'F';
                            }
                             
                            	document.getElementsByName("grade").value = grade;
                            }
                            }
                            
                            </script>

                            still doesn't work...


                            [PHP] <?php do { ?>
                            <tr>
                            <td height="20" scope="col"><in put name="matric_no[]" type="text" id="matric_no[]" value="<?php echo $row_test['matric_no']; ?>" size="10" readonly="true" /></td>
                            <td scope="col"><in put name="cam" type="int" id="cam" size="8" /></td>
                            <td scope="col" ><input name="final_exa m" type="int" id="final_exam " size="8" /></td>
                            <td scope="col"><in put name="total" type="int" id="total" size="8" onClick="calcul ate()"/></td>
                            <td scope="col"><in put name="grade" type="text" id="grade" size="8" onClick="gred() "/></td>
                            </tr>
                            <?php } while ($row_test = mysql_fetch_ass oc($test)); ?>
                            </table> [/PHP]

                            Comment

                            • RamananKalirajan
                              Contributor
                              • Mar 2008
                              • 608

                              #15
                              Are u passing an array of data from the PHP to html. Do You want to find the total for that? Is this your requirement

                              Regards
                              Ramanan Kalirajan

                              Comment

                              Working...