Sum inputs that id starts with

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kyriacoullis
    New Member
    • Jan 2010
    • 1

    #1

    Sum inputs that id starts with

    hi there,

    I have several forms that have a total field with the id gtotal1 gtotal2 gtotal3 ..... up to 35

    I would like a Grand Total of those fields. I would like to SUM those fields.

    I am looking for a code like:

    If input id contains gtotal then sum that inputs value.. something like that.

    I hope i was clear
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Hi Kyriacoullis,
    You can easily do that,

    Code:
    var totSum=0;
    for(var i=0;i<100;i++)
    {
      var tempId="gtotal"+i;
      try
      {
      if(document.getElementById(tempId).value!="")
          totSum+=document.getElementById(tempId).value;
      }
      catch(e)
      {
        alert(e.message);
      }
    }
    alert("Total Sum = "+totSum);
    Thanks and Regards
    Ramanan Kalirajan

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      the best would be to give each of those fields a common class name, so that you can access the elements with document.getEle mentsByClassNam e()

      EDIT: @Ramanan I think it’s not worth testing each ID, they are just not made for this purpose.

      Comment

      • RamananKalirajan
        Contributor
        • Mar 2008
        • 608

        #4
        @ Dormilich,
        Ya I am agreeing your point but document.getEle mentsByClassNam e() is not supported in IE. It will work fine in Mozilla. But it wont be working in IE, we have write a user defined function for that. But coding with ID will be working in all the browsers.

        Thanks and Regards
        Ramanan Kalirajan
        Last edited by RamananKalirajan; Jan 8 '10, 09:24 AM. Reason: Corrected the Signature

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          How about taking any good version of getElementsByCl assName and including it for any browsers that don't support it (by testing for its support):
          Code:
          if (!document.getElementsByClassName)

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            for instance Robert Nyman’s getElementsByCl assName()

            Comment

            Working...