Simple Function - but doesn't work!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • J. Hall

    Simple Function - but doesn't work!

    Hi dudes,

    Got a simple webpage, with three numeric text input boxes, the idea being
    that the user is asked to insert percentages of their business around the
    world...

    UK, Europe, Other

    Obviously this mustn't exceed 100% and so I OnChange I simply want to check
    that all three boxes have a value, and if so sum them up and alert the user
    is the sum exceeds 100!

    I have constructed the function below that WORKS but ONLY IF I remove the
    underscores from the Form Name and Input Boxes!? I'm totally confused by
    this, I haven't had this occurance before, and so I'm wondering if
    underscores are allowed in functions?

    Finally, how do I add an IF statement before the main IF statement to check
    for values in all three boxes?

    Many thanks!

    Please help!

    -------------------------------

    function Ash_CalculatePe rcentageTotal() {
    Num1 = document.form_a ddnewclient.Q_T urnoverPercentU K.value;
    Num2 = document.form_a ddnewclient.Q_T urnoverPercentE urope.value;
    Num3 = document.form_a ddnewclient.Q_T urnoverPercentO ther.value;

    alert('For debugging: ' + Num1 + ' ' + Num2 + ' ' + Num3)

    if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {
    alert('Please check the percentages entered, they must add up to 100%')
    }
    }





  • Lee

    #2
    Re: Simple Function - but doesn't work!

    J. Hall said:[color=blue]
    >
    >Hi dudes,
    >
    >Got a simple webpage, with three numeric text input boxes, the idea being
    >that the user is asked to insert percentages of their business around the
    >world...
    >
    >UK, Europe, Other
    >
    >Obviously this mustn't exceed 100% and so I OnChange I simply want to check
    >that all three boxes have a value, and if so sum them up and alert the user
    >is the sum exceeds 100!
    >
    >I have constructed the function below that WORKS but ONLY IF I remove the
    >underscores from the Form Name and Input Boxes!? I'm totally confused by
    >this, I haven't had this occurance before, and so I'm wondering if
    >underscores are allowed in functions?[/color]
    [color=blue]
    >function Ash_CalculatePe rcentageTotal() {
    > Num1 = document.form_a ddnewclient.Q_T urnoverPercentU K.value;
    > Num2 = document.form_a ddnewclient.Q_T urnoverPercentE urope.value;
    > Num3 = document.form_a ddnewclient.Q_T urnoverPercentO ther.value;
    >
    > alert('For debugging: ' + Num1 + ' ' + Num2 + ' ' + Num3)
    >
    >if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {
    >alert('Pleas e check the percentages entered, they must add up to 100%')
    > }
    >}[/color]

    If it works without the underscores, then my first guess
    is that the actual names in your HTML form don't have
    underscores, but you've neglected to show that code.

    What happens when it doesn't work? What error message
    do you see, or what bad result do you get?

    You don't need to use eval() to sum numbers.

    What happens if the sum is less than 100?

    Comment

    • J. Hall

      #3
      Re: Simple Function - but doesn't work!

      The underscores are in the code, the error message received is that 'the
      object could not be found' for each of the three elements, or that it is
      null - I can assure you the code is accurate from that point of view.

      Didn't realise I didn't need Eval, thanks for that. Still very odd relating
      to underscores, but I'll do some more investigation.. .

      Cheers, @sh


      "Lee" <REM0VElbspamtr ap@cox.net> wrote in message
      news:c9kl0t02ta 4@drn.newsguy.c om...[color=blue]
      > J. Hall said:[color=green]
      > >
      > >Hi dudes,
      > >
      > >Got a simple webpage, with three numeric text input boxes, the idea being
      > >that the user is asked to insert percentages of their business around the
      > >world...
      > >
      > >UK, Europe, Other
      > >
      > >Obviously this mustn't exceed 100% and so I OnChange I simply want to[/color][/color]
      check[color=blue][color=green]
      > >that all three boxes have a value, and if so sum them up and alert the[/color][/color]
      user[color=blue][color=green]
      > >is the sum exceeds 100!
      > >
      > >I have constructed the function below that WORKS but ONLY IF I remove the
      > >underscores from the Form Name and Input Boxes!? I'm totally confused by
      > >this, I haven't had this occurance before, and so I'm wondering if
      > >underscores are allowed in functions?[/color]
      >[color=green]
      > >function Ash_CalculatePe rcentageTotal() {
      > > Num1 = document.form_a ddnewclient.Q_T urnoverPercentU K.value;
      > > Num2 = document.form_a ddnewclient.Q_T urnoverPercentE urope.value;
      > > Num3 = document.form_a ddnewclient.Q_T urnoverPercentO ther.value;
      > >
      > > alert('For debugging: ' + Num1 + ' ' + Num2 + ' ' + Num3)
      > >
      > >if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {
      > >alert('Pleas e check the percentages entered, they must add up to 100%')
      > > }
      > >}[/color]
      >
      > If it works without the underscores, then my first guess
      > is that the actual names in your HTML form don't have
      > underscores, but you've neglected to show that code.
      >
      > What happens when it doesn't work? What error message
      > do you see, or what bad result do you get?
      >
      > You don't need to use eval() to sum numbers.
      >
      > What happens if the sum is less than 100?
      >[/color]


      Comment

      • Richard Cornford

        #4
        Re: Simple Function - but doesn't work!

        J. Hall wrote:[color=blue]
        > The underscores are in the code, the error message received
        > is that 'the object could not be found' for each of the three
        > elements, or that it is null - I can assure you the code is
        > accurate from that point of view.[/color]

        We can take your word for it that the accompanying HTML corresponds with
        your property accessors, in which case you are on your own, or you can
        show us the HTML so we can see if there are any obvious reasons for the
        failure of your script.

        As it stands we don’t know which browser is reporting these errors, 'the
        object could not be found' doesn’t sound like an IE error report. We don
        ’t know whether the HTML is HTML or XHTML (or XHTML being interpreted as
        HTML (appendix c compatibility XHTML)). We don’t know if the (X?)HTML is
        valid. We don’t know whether the identifiers in the script are
        referencing named form elements of IDed elements (or both). And then
        there are numerous other possible factors that might be impacting on
        your situation that would just take a moments visual inspection of the
        HTML to identify or rule out.

        Ultimately your best cause of action is to create a test case page,
        stripped down to just the form and accompanying (relevant) script, that
        demonstrates the problem. Posting that and allowing us to attempt to
        re-produce it in the browser that you are using, and others, will be
        your quickest route to understanding the problem. At least partly
        because making a striped down test case page often reveals the cause of
        the problem along the way (when you discover that stripping something
        that seemed irrelevant out coincidentally makes the problem vanish).
        [color=blue]
        > Didn't realise I didn't need Eval, ...[/color]
        <snip>

        There are so few genuine reasons for using - eval - that it is better to
        assume you don't ever need it. By the time you know enough to encounter
        a situation that might call for its use you should be able to be certain
        of that for yourself.

        Richard.


        Comment

        • Alberto

          #5
          Re: Simple Function - but doesn't work!

          Try this version, using parseFloat is easier, and the function, allowing now
          for arguments, is more flexible. I hope this helps

          <script language="JavaS cript"><!--

          function Ash_CalculatePe rcentageTotal(a rrayOfNames){
          /*
          @arrayOfNames= array of input fields without appending value: instance: new
          Array(document. formName.field1 , document.formNa me.field2)
          */
          if(typeof(array OfNames)!="obje ct"){return false;};
          var num=0;
          for(var i=0; i<arrayOfNames. length; i++){
          num+=parseFloat (arrayOfNames[i].value);
          }
          if(isNaN(num)|| num>100){
          alert("Please check the percentages entered, they must add up to 100% and
          must be numerical values"); return false;
          }
          /*you can delete this->*/alert(num);
          return num;
          }

          //--></script>
          </head>

          <body bgcolor="#fffff f" text="#000000">
          <form name="foo">
          <input name="name1">
          <input name="name2">
          <input name="name3">
          <input type="button" onClick="Ash_Ca lculatePercenta geTotal( [
          document.foo.na me1, document.foo.na me2, document.foo.na me3 ] )"
          value="Test">
          </form>

          ciao
          Alberto






          "J. Hall" <remove_this_as h@a-hall.com> ha scritto nel messaggio
          news:1086171726 .83156@news01.e clipse.net.uk.. .[color=blue]
          > Hi dudes,
          >
          > Got a simple webpage, with three numeric text input boxes, the idea being
          > that the user is asked to insert percentages of their business around the
          > world...
          >
          > UK, Europe, Other
          >
          > Obviously this mustn't exceed 100% and so I OnChange I simply want to[/color]
          check[color=blue]
          > that all three boxes have a value, and if so sum them up and alert the[/color]
          user[color=blue]
          > is the sum exceeds 100!
          >
          > I have constructed the function below that WORKS but ONLY IF I remove the
          > underscores from the Form Name and Input Boxes!? I'm totally confused by
          > this, I haven't had this occurance before, and so I'm wondering if
          > underscores are allowed in functions?
          >
          > Finally, how do I add an IF statement before the main IF statement to[/color]
          check[color=blue]
          > for values in all three boxes?
          >
          > Many thanks!
          >
          > Please help!
          >
          > -------------------------------
          >
          > function Ash_CalculatePe rcentageTotal() {
          > Num1 = document.form_a ddnewclient.Q_T urnoverPercentU K.value;
          > Num2 = document.form_a ddnewclient.Q_T urnoverPercentE urope.value;
          > Num3 = document.form_a ddnewclient.Q_T urnoverPercentO ther.value;
          >
          > alert('For debugging: ' + Num1 + ' ' + Num2 + ' ' + Num3)
          >
          > if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {
          > alert('Please check the percentages entered, they must add up to 100%')
          > }
          > }
          >
          >
          >
          >
          >[/color]


          Comment

          • J. Hall

            #6
            Re: Simple Function - but doesn't work!

            Hopefully this'll clear up a few elements...

            Straight ASP page with VB script, writing in standard HTML for form elements
            etc - here's the actual form itself...

            This is the version that works, as soon as I ad underscores into the form
            and input field names (within the body, and the function itself), it fails!!

            ----------------------------------------------------------------------------
            --------------

            <form action="process _clients.asp" method="post" name="formaddne wclient">
            <table width="600" height="25" border="0"
            cellpadding="0" cellspacing="0" >
            <tr>
            <td align="center" valign="middle" ><img
            src="graphics/common/horizontalline_ plain.gif" width="600" height="1"></td>
            </tr>
            </table>
            <table width="600" border="0" cellspacing="0"
            cellpadding="0" >
            <tr>
            <td align="center" valign="middle"
            class="MainText Body">&nbsp;</td>
            <td>&nbsp;</td>
            <td class="MainText Body">&nbsp;</td>
            </tr>
            <tr>
            <td width="30" align="center" valign="middle"
            class="MainText Body"><img src="graphics/bullets/medium.gif" width="6"
            height="6"></td>
            <td width="10"><img src="spacer.gif " width="10"
            height="3"></td>
            <td class="MainText Body">Percentag e of estimated
            turnover</td>
            </tr>
            </table>
            <table width="600" border="0" cellspacing="0"
            cellpadding="0" >
            <tr>
            <td width="30" align="center" valign="middle"
            class="MainText Body">&nbsp;</td>
            <td width="10"><img src="spacer.gif " width="10"
            height="3"></td>
            <td width="125" class="MainText Body">UK
            <input name="QTurnover PercentUK" type="text"
            class="AddAClie ntTextInput" id="QTurnoverPe rcentUK"
            onChange="javsc ript:Ash_Calcul atePercentageTo tal('formaddnew client');"
            value="0" size="6" maxlength="3">
            %</td>
            <td width="125" class="MainText Body">Europe
            <input name="QTurnover PercentEurope" type="text"
            class="AddAClie ntTextInput" id="QTurnoverPe rcentEurope"
            onChange="javsc ript:Ash_Calcul atePercentageTo tal('formaddnew client');"
            value="0" size="6" maxlength="3">
            %</td>
            <td width="125" class="MainText Body">Other
            <input name="QTurnover PercentOther" type="text"
            class="AddAClie ntTextInput" id="QTurnoverPe rcentOther"
            onChange="javsc ript:Ash_Calcul atePercentageTo tal('formaddnew client');"
            value="0" size="6" maxlength="3">
            %</td>
            <td class="MainText Body"><img src="spacer.gif "
            width="178" height="8"></td>
            </tr>
            </table>
            <table width="600" height="25" border="0"
            cellpadding="0" cellspacing="0" >
            <tr>
            <td align="center" valign="middle" ><img
            src="graphics/common/horizontalline_ plain.gif" width="600" height="1"></td>
            </tr>
            </table>
            </form>

            ----------------------------------------------------------------------------
            --------------

            ....now the function itself

            ----------------------------------------------------------------------------
            --------------

            function Ash_SubmitForm( TheFormName) {
            eval('document. '+TheFormName+' .submit();')
            }

            function Ash_CalculatePe rcentageTotal(T heForm) {
            var Num1 = eval('document. '+TheForm+'.QTu rnoverPercentUK .value');
            var Num2 = eval('document. '+TheForm+'.QTu rnoverPercentEu rope.value');
            var Num3 = eval('document. '+TheForm+'.QTu rnoverPercentOt her.value');

            if (Num1 > "" && Num2 > "" && Num3 > "") {

            if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {
            alert('Please check the percentages entered, they must add up to
            100%\n\nIf a region is equal to 0%, please enter a 0');
            }
            }
            }




            "Richard Cornford" <richard@litote s.demon.co.uk> wrote in message
            news:c9kusd$k3s $1@sparta.btint ernet.com...[color=blue]
            > J. Hall wrote:[color=green]
            > > The underscores are in the code, the error message received
            > > is that 'the object could not be found' for each of the three
            > > elements, or that it is null - I can assure you the code is
            > > accurate from that point of view.[/color]
            >
            > We can take your word for it that the accompanying HTML corresponds with
            > your property accessors, in which case you are on your own, or you can
            > show us the HTML so we can see if there are any obvious reasons for the
            > failure of your script.
            >
            > As it stands we don't know which browser is reporting these errors, 'the
            > object could not be found' doesn't sound like an IE error report. We don
            > 't know whether the HTML is HTML or XHTML (or XHTML being interpreted as
            > HTML (appendix c compatibility XHTML)). We don't know if the (X?)HTML is
            > valid. We don't know whether the identifiers in the script are
            > referencing named form elements of IDed elements (or both). And then
            > there are numerous other possible factors that might be impacting on
            > your situation that would just take a moments visual inspection of the
            > HTML to identify or rule out.
            >
            > Ultimately your best cause of action is to create a test case page,
            > stripped down to just the form and accompanying (relevant) script, that
            > demonstrates the problem. Posting that and allowing us to attempt to
            > re-produce it in the browser that you are using, and others, will be
            > your quickest route to understanding the problem. At least partly
            > because making a striped down test case page often reveals the cause of
            > the problem along the way (when you discover that stripping something
            > that seemed irrelevant out coincidentally makes the problem vanish).
            >[color=green]
            > > Didn't realise I didn't need Eval, ...[/color]
            > <snip>
            >
            > There are so few genuine reasons for using - eval - that it is better to
            > assume you don't ever need it. By the time you know enough to encounter
            > a situation that might call for its use you should be able to be certain
            > of that for yourself.
            >
            > Richard.
            >
            >[/color]


            Comment

            • Richard Cornford

              #7
              Re: Simple Function - but doesn't work!

              J. Hall wrote:[color=blue]
              > Hopefully this'll clear up a few elements...
              >
              > Straight ASP page with VB script, writing in standard HTML for form
              > elements etc - here's the actual form itself...
              >
              > This is the version that works, as soon as I ad underscores into the
              > form and input field names (within the body, and the function
              > itself), it fails!![/color]

              So I propose you create a test case page that demonstrates the problem
              in isolation and you respond by posting code that doesn't exhibit the
              problem, but does include a mass of irrelevant noise.
              [color=blue]
              > <form action="process _clients.asp" method="post"
              > name="formaddne wclient">
              > <table width="600" height="25" border="0"
              > cellpadding="0" cellspacing="0" >[/color]
              ....[color=blue]
              > </table>
              > <table width="600" border="0" cellspacing="0"
              > cellpadding="0" >[/color]
              ....[color=blue]
              > </table>
              > <table width="600" border="0" cellspacing="0"
              > cellpadding="0" >[/color]
              ....[color=blue]
              > </table>
              > <table width="600" height="25" border="0"
              > cellpadding="0" cellspacing="0" >[/color]
              ....[color=blue]
              > </table>
              > </form>[/color]

              You badly need to learn HTML and CSS. This code is really bloated for
              what it is. Just removing the obvious redundancies will half its size,
              knowing how to author and style HTML would reduce the total by about a
              factor of 20.

              Bloated HTML has obvious consequences for the user's download time,
              server load and bandwidth consumption. Those may not be considered
              significant (at least by those that think everyone (at least everyone
              that matters) is on broadband), but as soon as a web site goes beyond
              the machine (Dreamweaver) generation of HTML and starts employing people
              to manipulate that HTML (sever or client-side) unnecessary code bloat
              starts to impact on development costs. Because the more HTML there is
              the longer it takes to find anything in that HTML. Maybe often just
              fractions of a second longer but it adds up, and it adds up at expensive
              software developer hourly rates.

              There is also an increasing tendency to attempt to use HTTP request
              objects to avoid re-loading web pages, with their consequential
              javascript dependencies, limited browser support and increased
              complexity. I often wonder to what extent this trend is motivated by
              HTML that has become so bloated that an ordinary HTTP request followed
              by loading a page from the server has become so slow as to motivate its
              authors to look for an alternative. Solving the wrong problem, when
              authoring efficient HTML would have avoided the problem manifesting
              itself in the first place.
              [color=blue]
              > function Ash_SubmitForm( TheFormName) {[/color]

              I found no evidence that of this function being called at any point. As
              it is the only way that the form can be submitted I am forced to
              question you assertion that this code "works".
              [color=blue]
              > eval('document. '+TheFormName+' .submit();')[/color]

              When I said that it was best to assume that you never need to use -
              eval - I meant it. Using - eval - to execute dynamically constructed dot
              notation property accessors is always unnecessary as javascript offers
              bracket notation property accessors as an alternative, and they
              facilitate the dynamic construction of property names:-

              document[TheFormName].submit();
              [color=blue]
              > }
              >
              > function Ash_CalculatePe rcentageTotal(T heForm) {
              > var Num1 = eval('document. '+TheForm+'.QTu rnoverPercentUK .value');[/color]

              var Num1 = document[+TheForm].QTurnoverPerce ntUK.value;
              [color=blue]
              > var Num2 = eval('document. '+TheForm+'.QTu rnoverPercentEu rope.value');[/color]

              var Num2 = document[TheForm].QTurnoverPerce ntEurope.value;
              [color=blue]
              > var Num3 = eval('document. '+TheForm+'.QTu rnoverPercentOt her.value');[/color]

              var Num3 =document[TheForm].QTurnoverPerce ntOther.value;
              [color=blue]
              > if (Num1 > "" && Num2 > "" && Num3 > "") {
              >
              > if (eval(Number(Nu m1)+Number(Num2 )+Number(Num3)) > 100) {[/color]

              if ((Number(Num1)+ Number(Num2)+ Number(Num3)) > 100) {

              - or:-

              if (((+Num1)+(+Num 2)+(+Num3)) > 100) {

              (Additional checks are required in this testing as a user entering
              non-numeric data will result in that field being converted to NaN and so
              the sum will be NaN and NaN is never > 100 (or < 100))
              [color=blue]
              > alert('Please check the percentages entered, they must add up to
              > 100%\n\nIf a region is equal to 0%, please enter a 0');
              > }
              > }
              > }[/color]

              <URL: http://jibbering.com/faq/#FAQ4_39 >

              One of the factors (though a relatively minor one) that motivates people
              to recommend against using - eval - is that it re-locates and conceals
              error producing code.

              The underscore character is allowed in any location within a javascript
              identifier and dot notation property accessors only require that valid
              identifiers are used (bracket notation is not so restrictive). There is
              nothing here that would suggest a reason why the code that you are not
              showing us is not working.

              On the other hand, I wonder about the logic of the process and the form.
              You are asking for percentages of turnover originating in the UK, Europe
              and Other, and insisting that those percentages add up to 100%. However,
              those three groups cover everywhere, so why can't the user fill in
              Europe and UK figures and leave your (server-side) code to work out that
              Other must be whatever is left when UK and Europe is subtracted from
              100%. The form would be easier to fill in and you would get exactly the
              same information from it.
              [color=blue]
              > "Richard Cornford" <richard@litote s.demon.co.uk> wrote ...[/color]
              <sniped verbatim quote of preceding message>

              Please do not top-post to comp.lang.javas cript. If you don't want people
              to help you it would be simple to not post at all.

              Richard.


              Comment

              • Dr John Stockton

                #8
                Re: Simple Function - but doesn't work!

                JRS: In article <c9nfvb$fsv$1$8 302bc10@news.de mon.co.uk>, seen in
                news:comp.lang. javascript, Richard Cornford
                <Richard@litote s.demon.co.uk> posted at Thu, 3 Jun 2004 16:26:34 :[color=blue]
                >
                >if (((+Num1)+(+Num 2)+(+Num3)) > 100) {
                >
                >(Additional checks are required in this testing as a user entering
                >non-numeric data will result in that field being converted to NaN and so
                >the sum will be NaN and NaN is never > 100 (or < 100))[/color]

                No, not additional. Either of the following should suffice :

                if ( ! (((+Num1)+(+Num 2)+(+Num3)) <= 100) ) {
                if ( ! ( +Num1 + +Num2 + +Num3 <= 100) ) {

                Consider them as if not right then ...

                --
                © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
                <URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
                <URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.

                Comment

                Working...