structure and effeciency on simple function advice please

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

    structure and effeciency on simple function advice please

    Can this be refined further to be more efficient?

    function shout()
    {
    if (isNaN(document .form1.entry.va lue)==true) {
    alert("please only enter numbers for an answer")}
    else
    {
    alert("the new number is: "+(+document.fo rm1.entry.value +5))}
    }


    also what would be the correct structure as to make the script more legible
    to regular and proficient writers of JS?

    thanks!



    ...b..


  • Michael Winter

    #2
    Re: structure and effeciency on simple function advice please

    On Sat, 11 Sep 2004 14:54:12 +0000 (UTC), badstyle
    <phatwap-spam01@yahoo.co .uk> wrote:
    [color=blue]
    > Can this be refined further to be more efficient?[/color]

    If there was more to this function, there might be other optimisations.
    Was there anything in particular you were considering?
    [color=blue]
    > function shout()
    > {
    > if (isNaN(document .form1.entry.va lue)==true) {[/color]

    It would be simpler to use:

    if(isNaN(...)) {

    The comparison is unnecessary. However, it's not the best way to check for
    numeric input. I'll present a better approach below, but it's very generic
    and might not be what you'd really want.
    [color=blue]
    > alert("please only enter numbers for an answer")}
    > else
    > {
    > alert("the new number is: "+(+document.fo rm1.entry.value +5))}[/color]

    As you use the element reference more than once, it's best to save that
    reference. It avoids the need to resolve properties repeatedly.
    [color=blue]
    > also what would be the correct structure as to make the script more
    > legible to regular and proficient writers of JS?[/color]

    Try:

    function shout() {
    // Save reference to form element
    var e = document.forms['form1'].elements['entry'];
    // Check for only integers
    if(!/^\d+$/.test(e.value)) {
    alert('Please restrict values to numbers only.');
    } else {
    alert('The new number is ' + (+e.value + 5) + '.');
    }
    }

    Hope that helps,
    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.

    Comment

    • Evertjan.

      #3
      Re: structure and effeciency on simple function advice please

      Michael Winter wrote on 11 sep 2004 in comp.lang.javas cript:
      [color=blue]
      > function shout() {
      > // Save reference to form element
      > var e = document.forms['form1'].elements['entry'];
      > // Check for only integers
      > if(!/^\d+$/.test(e.value)) {
      > alert('Please restrict values to numbers only.');
      > } else {
      > alert('The new number is ' + (+e.value + 5) + '.');
      > }
      > }
      >[/color]

      Slightly more optimalisation is possible:

      function shout() {
      var e = document.forms['form1'].elements['entry'].value;
      alert(
      (/^\d+$/.test(e))?
      'The new number is ' + (+e + 5) + '.':
      'Please restrict values to numbers only.')
      }



      --
      Evertjan.
      The Netherlands.
      (Please change the x'es to dots in my emailaddress,
      but let us keep the discussions in the newsgroup)

      Comment

      • Michael Winter

        #4
        Re: structure and effeciency on simple function advice please

        On 11 Sep 2004 16:10:23 GMT, Evertjan. <exjxw.hannivoo rt@interxnl.net >
        wrote:

        [snip]
        [color=blue]
        > function shout() {
        > var e = document.forms['form1'].elements['entry'].value;[/color]

        I made the assumption that if there was a new number, the element might
        want to be modified, or accessed in some other way, like calling focus
        should the validation fail. But yes, if only the value is needed, then
        save that.
        [color=blue]
        > alert(
        > (/^\d+$/.test(e))?
        > 'The new number is ' + (+e + 5) + '.':
        > 'Please restrict values to numbers only.')[/color]

        I can't say I'd have considered that, but then again, it's a rather
        artificial example and I don't think it would occur in a real setting.

        Mike

        --
        Michael Winter
        Replace ".invalid" with ".uk" to reply by e-mail.

        Comment

        • Evertjan.

          #5
          Re: structure and effeciency on simple function advice please

          Michael Winter wrote on 11 sep 2004 in comp.lang.javas cript:
          [color=blue][color=green]
          >> alert(
          >> (/^\d+$/.test(e))?
          >> 'The new number is ' + (+e + 5) + '.':
          >> 'Please restrict values to numbers only.')[/color]
          >
          > I can't say I'd have considered that, but then again, it's a rather
          > artificial example and I don't think it would occur in a real setting.
          >[/color]

          'cause not, but the OP specified "more efficient".

          My solution will be unreadable for the newbee, I presume.

          --
          Evertjan.
          The Netherlands.
          (Please change the x'es to dots in my emailaddress,
          but let us keep the discussions in the newsgroup)

          Comment

          • badstyle

            #6
            Re: structure and effeciency on simple function advice please

            "Evertjan." <exjxw.hannivoo rt@interxnl.net > wrote in message
            news:Xns9561C01 2F7A40eejj99@19 4.109.133.29...
            [color=blue][color=green][color=darkred]
            >>> alert(
            >>> (/^\d+$/.test(e))?
            >>> 'The new number is ' + (+e + 5) + '.':
            >>> 'Please restrict values to numbers only.')[/color]
            >>
            >> I can't say I'd have considered that, but then again, it's a rather
            >> artificial example and I don't think it would occur in a real setting.
            >>[/color]
            >
            > 'cause not, but the OP specified "more efficient".
            >
            > My solution will be unreadable for the newbee, I presume.
            >[/color]

            you're right, to me it is extremely unreadable at the moment! :)

            I understand what it is [in my mind] supposed to be doing, based on my
            meagre attempt and knowing that allows me to dissect this more "tech savvy"
            interpretation and get my mind into understanding these alternative methods.

            Thanks people, much appreciated! :)


            ...b..


            Comment

            • Dr John Stockton

              #7
              Re: structure and effeciency on simple function advice please

              JRS: In article <chv3ik$5oc$1@h ercules.btinter net.com>, dated Sat, 11
              Sep 2004 14:54:12, seen in news:comp.lang. javascript, badstyle <phatwap-
              spam01@yahoo.co .uk> posted :
              [color=blue]
              >Can this be refined further to be more efficient?[/color]

              Yes.
              [color=blue]
              > function shout()
              > {
              > if (isNaN(document .form1.entry.va lue)==true) {
              > alert("please only enter numbers for an answer")}
              > else
              > {
              > alert("the new number is: "+(+document.fo rm1.entry.value +5))}
              > }
              >
              >
              >also what would be the correct structure as to make the script more legible
              >to regular and proficient writers of JS?[/color]

              "Never" use ==true (except as an indicator of ignorance).

              "Numbers" includes such as -1.2345e6, 5e9999, funf-und-funfzig, MCMXLIV,
              0x3F5. Perhaps you mean decimal digits? isNaN is generally an
              inadequate test. See my js-valid.htm.

              Indent two or three spaces, consistently, for each currently-unfinished
              language construct.

              Use var Ent = document.form1. entry

              Omit +( and one ) . Put spaces around concatenating + .

              Reword the failure alert.

              --
              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
              <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

              Comment

              • Thomas 'PointedEars' Lahn

                #8
                Re: structure and effeciency on simple function advice please

                badstyle wrote:
                ^^^^^^^^
                Your "name" is program?
                [color=blue]
                > Can this be refined further to be more efficient?
                >
                > function shout()
                > {
                > if (isNaN(document .form1.entry.va lue)==true) {
                > alert("please only enter numbers for an answer")}
                > else
                > {
                > alert("the new number is: "+(+document.fo rm1.entry.value +5))}
                > }
                >
                > also what would be the correct structure as to make the script more
                > legible to regular and proficient writers of JS?[/color]

                <head>
                ...
                <script type="text/javascript">
                function shout(f, sName)
                {
                var o = null;
                if (f && (o = f.elements) && (o = o[sName]))
                {
                if (isNaN(o.value) )
                {
                alert("Please only enter numbers for an answer.");
                }
                else
                {
                alert("The new number is: " + (+o.value + 5));
                }
                }
                }
                </script>
                ...
                </head>

                <body>
                ...
                <form action="...">
                ...
                <input name="entry">
                ...
                <script type="text/javascript">
                document.write(
                '<input type="button" onclick="shout( this.form, \'entry\')">');
                </script>
                ...
                </form>
                ...
                </body>


                PointedEars

                Comment

                Working...