altering text with javascript

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

    altering text with javascript

    Dear All,

    Hopefully I have a simple problem. Basically, I just want to alter some text
    with JS.

    Here is some of my test code:

    <snip>
    <script type="text/javascript">
    var tmp='a';

    function myfunction(){
    tmp='b';
    }
    </script>

    <input type="button" onClick=javascr ipt:myfunction( ) >
    <script type="text/javascript">
    document.write( tmp);
    </script>
    <snip>

    So when variable tmp is updated, I want to change the 'document.write (tmp)'
    to reflect this.

    If there is a better of changing text, feel free to suggest it.

    Many thanks

    Colin


  • Robert

    #2
    Re: altering text with javascript

    In article <cj19vt$4fk$1@u csnew1.ncl.ac.u k>,
    "C Gillespie" <csgcsg39@hotma il.com> wrote:[color=blue]
    > Hopefully I have a simple problem. Basically, I just want to alter some text
    > with JS.
    >
    > Here is some of my test code:[/color]
    [color=blue]
    > <input type="button" onClick=javascr ipt:myfunction( ) >
    > <script type="text/javascript">
    > document.write( tmp);
    > </script>
    > <snip>[/color]

    1) The document.write may only be used when the document is first
    loaded.

    2) There is no need for javascript: in an event handler. Javascript is
    assumed in all event handler such as onclick.

    3) It is best to put quotes around the javascript code in an event
    handler. onClick="myfunc tion();"

    4) It is best to put in the trailing semi-colon ";".

    You need to access the document node structure to insert the text. Here
    is an example of this, Robert:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>insert some text</title>

    <script type="text/javascript">
    function changeText(labe l,text)
    {
    var node;
    if (document.getEl ementById)
    {
    var node = document.getEle mentById(label) ;
    if (node)
    {
    /*See if we already inserted a node. */
    var nextNode = node.firstChild ;
    if(nextNode)
    {
    /* Yes, replace the text. */
    nextNode.data = text.value;
    }
    else
    {
    /* No, Insert the new node. */
    node.appendChil d(
    document.create TextNode(text.v alue));
    node.text = text;
    }
    }
    else
    {
    alert("You need to create a span tag with " +

    "the id of " + label + ".");
    return;
    }
    }
    else
    {
    alert(" document.getEle mentByID failed. " +
    "You need to use a newer browser.");
    return;
    }

    }

    </script>
    </head>
    <body>
    <p>Insert or change some text.
    <br>
    Don't forget to see what happens when you
    press the button more than once.</p>
    <form id="myForm">
    <input type="text" name="total" size="20">
    <br><br>
    <input type="button"
    name="activate"
    value="change the text"
    onclick="change Text('insert',
    document.forms['myForm'].elements['total']);">
    <br>
    </form>
    <p>Change this "
    <span id='insert'>
    </span>".</p>
    </body>
    </html>

    Comment

    • simina

      #3
      Re: altering text with javascript

      I tried too but in a different manner...
      Hope it helps:

      <form>
      <input type="text" name="myText" value="a">
      <input type="button" name="myButton" onClick="return
      myfunction(this .form);">
      </form>

      <script language="JavaS cript1.2" type="text/javascript">
      function myfunction(frm)
      {
      frm.myText.valu e = "b";
      }
      </script>

      If you don't want the "a" to be in a text field, but just a text I
      don't konw how to do it...
      S.

      Comment

      • Dr John Stockton

        #4
        Re: altering text with javascript

        JRS: In article <rccharles-0456B0.14045224 092004@news1.we st.earthlink.n
        et>, dated Fri, 24 Sep 2004 17:58:55, seen in news:comp.lang. javascript,
        Robert <rccharles@my-deja.com> posted :[color=blue]
        >
        >You need to access the document node structure to insert the text. Here
        >is an example of this, Robert:[/color]

        That way will, I think, not work in as many browsers as the method in
        our FAQ, 4.15.

        There is no need to require getElementById ; see past posts here, and my
        page js-other.htm , for generating it, briefly.

        --
        © 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

        • Robert

          #5
          Re: altering text with javascript

          In article <vw43QEOc+KVBFw x$@merlyn.demon .co.uk>,
          Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:
          [color=blue]
          >That way will, I think, not work in as many browsers as the method in
          >our FAQ, 4.15.[/color]

          I do not follow ever detail about the code in this section, but it seems
          to use innerHTML which I understand isn't in W3C.
          [color=blue]
          > There is no need to require getElementById ; see past posts here, and my
          > page js-other.htm , for generating it, briefly.[/color]


          I added the code to support documnent.all and did some general fix up.

          I tested this code on safari 1.0, Netscape 7.2, and IE 5.2 on MacOS
          10.2.6. I test on Windows 95 with IE 4.72 to invoke the document.all
          code.

          I consider this more of a proof of concept than a final code. It would
          require more testing to verify that it worked with the browsers one
          wanted to support.

          Robert

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
          <html>
          <head>
          <title>insert some text</title>

          <script type="text/javascript">
          function changeText(labe l,text)
          {
          var node;
          if (document.getEl ementById)
          {
          var node = document.getEle mentById(label) ;
          if (node)
          {
          /*See if we already inserted a node. */
          var nextNode = node.firstChild ;
          if(nextNode)
          {
          /* Yes, replace the text. */
          nextNode.data = text.value;
          }
          else
          {
          /* No, Insert the new node. */
          node.appendChil d(
          document.create TextNode(text.v alue));
          }
          }
          else
          {
          alert("You need to create a span tag with " +

          "the id of " + label + ".");
          return;
          }
          }
          else
          {
          if (document.all)
          {
          document.all[label].innerHTML = text.value;
          }
          else
          {
          alert("Construc ts document.getEle mentByID " +
          "and document.all failed. " +
          "You need to use a newer browser.");
          return;
          }
          }

          }

          </script>
          </head>
          <body>
          <p>Insert or change some text.
          <br>
          Don't forget to see what happens when you
          press the button more than once.</p>
          <form name="myForm">
          <input type="text" name="total" size="20">
          <br><br>
          <input type="button"
          name="activate"
          value="change the text"
          onclick="change Text('insert',
          document.forms['myForm'].elements['total']);">
          <br>
          </form>
          <p>Change this "<span id='insert'>
          </span>".</p>
          </body>
          </html>

          Comment

          • Michael Winter

            #6
            Re: altering text with javascript

            On Sat, 25 Sep 2004 04:33:17 GMT, Robert <rccharles@my-deja.com> wrote:
            [color=blue]
            > In article <vw43QEOc+KVBFw x$@merlyn.demon .co.uk>,
            > Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:
            >[color=green]
            >> That way will, I think, not work in as many browsers as the method in
            >> our FAQ, 4.15.[/color]
            >
            > I do not follow ever detail about the code in this section, but it seems
            > to use innerHTML which I understand isn't in W3C.[/color]

            It's not, but a lot of browsers do support it.
            [color=blue][color=green]
            >> There is no need to require getElementById ; see past posts here, and
            >> my page js-other.htm , for generating it, briefly.[/color]
            >
            > I added the code to support documnent.all and did some general fix up.[/color]

            Note: I'm not correcting you, just suggesting a different approach.

            Here's the code I use for gEBI and d.all support (part of a larger
            collection of code):

            var domCore = (function() {
            function isN(o) {return 'number' == typeof o;}
            return ({
            getElementById : document.getEle mentById ?
            function(n) {return document.getEle mentById(n);}
            : document.all ?
            function(n) {
            var e = document.all[n], i = e.length;
            if(isN(i)) {while(i--) {if(e[i].id == n) return e[i];}}
            else if(e.id == n) {return e;}
            return null;
            }
            : function() {return null;}
            });
            })();

            It tries to ensure that only one element is returned by the all
            collection, and that that element was retrieved by its id, only.

            You could then test whether innerHTML was supported with a typeof test:

            var node = domCore.getElem entById(label);
            if(node) {
            var child;
            if('string' == typeof node.innerHTML) {
            node.innerHTML = text.value;
            } else if((child = node.firstChild )) {
            child.data = text.value;
            } else if(document.cre ateTextNode && node.appendChil d) {
            node.appendChil d(document.crea teTextNode(text .value));
            }
            }

            Probably a better way than that, though.

            [snip]

            Mike

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

            Comment

            • Robert

              #7
              Re: altering text with javascript

              "Michael Winter" <M.Winter@bluey onder.co.invali d> wrote in message news:<opsevovyv zx13kvk@atlanti s>...[color=blue]
              > On Sat, 25 Sep 2004 04:33:17 GMT, Robert <rccharles@my-deja.com> wrote:
              >[color=green]
              > > In article <vw43QEOc+KVBFw x$@merlyn.demon .co.uk>,
              > > Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:
              > >[/color][/color]
              [color=blue]
              > Note: I'm not correcting you, just suggesting a different approach.
              >
              > Here's the code I use for gEBI and d.all support (part of a larger
              > collection of code):
              >
              > var domCore = (function() {
              > function isN(o) {return 'number' == typeof o;}
              > return ({
              > getElementById : document.getEle mentById ?
              > function(n) {return document.getEle mentById(n);}
              > : document.all ?
              > function(n) {
              > var e = document.all[n], i = e.length;
              > if(isN(i)) {while(i--) {if(e[i].id == n) return e[i];}}
              > else if(e.id == n) {return e;}
              > return null;
              > }
              > : function() {return null;}
              > });
              > })();
              >
              > It tries to ensure that only one element is returned by the all
              > collection, and that that element was retrieved by its id, only.[/color]

              This will take some study. I realize that this is copied code. Any
              advantages of nesting the code in the return statement. You did end
              up rather deep in all of these )}.
              [color=blue]
              >
              > You could then test whether innerHTML was supported with a typeof test:
              >
              > var node = domCore.getElem entById(label);
              > if(node) {
              > var child;
              > if('string' == typeof node.innerHTML) {
              > node.innerHTML = text.value;
              > } else if((child = node.firstChild )) {
              > child.data = text.value;
              > } else if(document.cre ateTextNode && node.appendChil d) {
              > node.appendChil d(document.crea teTextNode(text .value));
              > }
              > }
              >[/color]

              Dr John Stockton wants to add a code path that doesn't require the use
              of getElementById( ).

              While I didn't think of useing innerHTML for this, I'd think that
              using innerHTML would be slower than inserting the node directly.

              I thought that side effects are questionable. I see an if statement
              as a structure to test something so I do not expect things to change
              inside of the if statement.

              Robert

              Comment

              • Richard Cornford

                #8
                Re: altering text with javascript

                Robert wrote:[color=blue]
                > Michael Winter wrote:[/color]
                <snip>[color=blue][color=green]
                >> Note: I'm not correcting you, just suggesting a different
                >> approach.[/color][/color]
                [color=blue][color=green]
                >> Here's the code I use for gEBI and d.all support (part of
                >> a larger collection of code):
                >>
                >> var domCore = (function() {
                >> function isN(o) {return 'number' == typeof o;}
                >> return ({
                >> getElementById : document.getEle mentById ?
                >> function(n) {return document.getEle mentById(n);}
                >> : document.all ?
                >> function(n) {
                >> var e = document.all[n], i = e.length;[/color][/color]
                ^
                Isn't it a bit premature to be assuming that the - document.all -
                collection has returned something at this point? Any undefined (or null)
                value will error at the reading of - e.length -. I suppose you could
                assign a value to e with a logical OR expression where undefined or null
                would result in a right hand side value that could be type converted
                for - e.length - and - e.id -, returning undefined at that point. A
                number or boolean literal should be practical as their object
                representations lack both properties (which is not true of a string):-

                var e = (document.all[id] || false);
                - or:-
                var e = (document.all[id] || 0);

                - or an explicit object that has no - length - or - id - property:-

                var e = (document.all[id] || {} );
                [color=blue][color=green]
                >> if(isN(i)) {while(i--) {if(e[i].id == n) return e[i];}}
                >> else if(e.id == n) {return e;}
                >> return null;
                >> }
                >> : function() {return null;}
                >> });
                >> })();
                >>
                >> It tries to ensure that only one element is returned by
                >> the all collection, and that that element was retrieved
                >> by its id, only.[/color]
                >
                > This will take some study. I realize that this is copied
                > code. Any advantages of nesting the code in the return
                > statement.[/color]

                Function expressions do not result in the creation of a corresponding
                function object until they are evaluated. So while it would be possible
                to define all of the possible assigned functions with inner function
                declarations their appearance as expressions in the conditional
                statement means that only the one function expression evaluated will
                result in the creation of a function object (which is faster in
                execution than creating 3 as would happen with separate inner function
                declarations).
                [color=blue]
                > You did end up rather deep in all of these )}.[/color]

                The resulting code looks convoluted but once you are used to seeing
                function expressions, and assuming the code is indented to express
                structure and parenthesised to highlight the precedence in expression
                evaluation, it is not nearly as complex as it might at first appear.

                Personally I might have been inclined to put a few more parentheses in.
                Around the conditional expression and maybe its contained function
                expressions. But you can go overboard with parentheses, and javascript
                authors should be capable of recognising where an expression is implied
                by its context in most situations anyway.
                [color=blue][color=green]
                >> You could then test whether innerHTML was supported with
                >> a typeof test:[/color][/color]

                While a - typepf - test will indicate the existence of an innerHTML
                property (of string type), it has been suggested that innerHTML might be
                available as a read-only property on some less-dynamic browsers (I don't
                recall whether specific examples have ever been cited). Hence the more
                elaborate strategy in the notes for #4.15.
                [color=blue][color=green]
                >> var node = domCore.getElem entById(label);
                >> if(node) {
                >> var child;
                >> if('string' == typeof node.innerHTML) {
                >> node.innerHTML = text.value;
                >> } else if((child = node.firstChild )) {
                >> child.data = text.value;
                >> } else if(document.cre ateTextNode && node.appendChil d) {
                >> node.appendChil d(document.crea teTextNode(text .value));
                >> }
                >> }
                >>[/color]
                >
                > Dr John Stockton wants to add a code path that doesn't require
                > the use of getElementById( ).[/color]

                But this code calls - domCore.getElem entById -, a method of the object
                set-up in the first example block of code. And that doesn't require -
                document.getEle mentById -.
                [color=blue]
                > While I didn't think of useing innerHTML for this, I'd
                > think that using innerHTML would be slower than inserting
                > the node directly.[/color]

                Using innerHTML makes most sense when attempting to change more than
                just the text of one text Node (i.e. To insert a branch of a DOM tree,
                especially when that branch is defined a string of HTML source code).
                [color=blue]
                > I thought that side effects are questionable. I see an
                > if statement as a structure to test something so I do
                > not expect things to change inside of the if statement.[/color]

                Moving the assignment expression outside of the - if - statement means
                having a second - if/else - inside the - else - clause of a first.
                Whatever might be gained in attempting to clarify that one - if -
                statement can be weighed against losing the clear one-of-three structure
                in the containing code. Parenthesising the assignment expression within
                the - if - expression should make it clear that the assignment precedes
                the evaluation of the - if - expression, which is based on the result of
                the assignment expression.

                Richard.


                Comment

                • Robert

                  #9
                  Re: altering text with javascript

                  "Richard Cornford" <Richard@litote s.demon.co.uk> wrote in message news:<2rloulF1b buoiU1@uni-berlin.de>...
                  [color=blue]
                  >
                  > You could then test whether innerHTML was supported with a typeof test:
                  >
                  > var node = domCore.getElem entById(label);
                  > if(node) {
                  > var child;
                  > if('string' == typeof node.innerHTML) {
                  > node.innerHTML = text.value;
                  > } else if((child = node.firstChild )) {
                  > child.data = text.value;
                  > } else if(document.cre ateTextNode && node.appendChil d) {
                  > node.appendChil d(document.crea teTextNode(text .value));
                  > }
                  > }
                  >[/color]
                  [color=blue][color=green]
                  > > I thought that side effects are questionable. I see an
                  > > if statement as a structure to test something so I do
                  > > not expect things to change inside of the if statement.[/color]
                  >
                  > Moving the assignment expression outside of the - if - statement means
                  > having a second - if/else - inside the - else - clause of a first.
                  > Whatever might be gained in attempting to clarify that one - if -
                  > statement can be weighed against losing the clear one-of-three structure[/color]

                  You have to mentally insert the assignment statement and realize that
                  it isn't a conditional thing. My thought process is that I have to
                  push the if statement down in my thinking. Remember the assignment.
                  Then, I have to recall the if statement. You can see from my
                  formatting of the code. That I do not have to do this mental activity
                  because it is written on paper.

                  At least for me, I have to do the translation in my head. It is more
                  complicated for me to understand.
                  [color=blue]
                  > in the containing code. Parenthesising the assignment expression within
                  > the - if - expression should make it clear that the assignment precedes
                  > the evaluation of the - if - expression, which is based on the result of
                  > the assignment expression.[/color]

                  I reformulated the logic here.

                  var node = domCore.getElem entById(label);
                  if(node)
                  {
                  var child;
                  if('string' == typeof node.innerHTML)
                  {
                  node.innerHTML = text.value;
                  }
                  else
                  {
                  child = node.firstChild ;
                  if(child)
                  {
                  child.data = text.value;
                  }
                  else if(document.cre ateTextNode &&
                  node.appendChil d)
                  {
                  node.appendChil d(
                  document.create TextNode(text.v alue));
                  }
                  }
                  }



                  Shows clearly:

                  1) What goes with what
                  2) code parrallels the oder the machine will run the code. You do not
                  have to back scan in the if statment nor do mental push and pop
                  operations.
                  3) avoids the confusion over = and ==
                  4) Hilights the assignment statement because is valid for the rest of
                  the code block. It is valid outside the rest of the if statement. I
                  believe this reason alone is something you want to hilight. Don't try
                  to hide the assignment in the if statement where it is easier to miss
                  than if it had it's own line of code.

                  You can see from the format of the code that I like to understand one
                  simple
                  thing at a time then go onto the next thing.

                  In examples to folks who are not as familiar with program, I believe
                  it is best to code things in an easy to understand format and avoid
                  coding styles that many programs have noted as problematic. Look at
                  the code posted to this forum and note the problems with it.

                  Even though you may like using an assignment statement in an if
                  statement many programmer have found it troublesome. I assume this
                  must be getting at something. Best to avoid troublesome situations.

                  Thanks for you other comments.

                  You are a great asset to this forum.

                  Robert

                  Comment

                  • Robert

                    #10
                    Re: altering text with javascript

                    spetrusa@yahoo. com (simina) wrote in message news:<881883f0. 0409241317.27c6 eee9@posting.go ogle.com>...[color=blue]
                    > I tried too but in a different manner...
                    > Hope it helps:
                    >
                    > <form>
                    > <input type="text" name="myText" value="a">
                    > <input type="button" name="myButton" onClick="return
                    > myfunction(this .form);">
                    > </form>
                    >
                    > <script language="JavaS cript1.2" type="text/javascript">[/color]

                    Language has been depreciated in favor of type.

                    <script type="text/javascript">

                    Best to leave out JavaScript1.2. Version 1.2 acted a little different
                    from the other versions of Javascript.
                    [color=blue]
                    > function myfunction(frm)
                    > {
                    > frm.myText.valu e = "b";
                    > }
                    > </script>
                    >
                    > If you don't want the "a" to be in a text field, but just a text I
                    > don't konw how to do it...
                    > S.[/color]

                    This is valid:

                    <input type="text" name="myText" value="">

                    You should start a new thread if this is not what you are looking for.

                    I do not understand this comment:
                    but just a text

                    I assume you meant a blank text field.

                    You can hide the input field until you need it. Ask again if this is
                    what you wanted.


                    Robert

                    Comment

                    • Richard Cornford

                      #11
                      Re: altering text with javascript

                      Robert wrote:[color=blue]
                      > Richard Cornford wrote:[/color]
                      <snip>[color=blue][color=green]
                      >> Moving the assignment expression outside of the - if -
                      >> statement means having a second - if/else - inside the
                      >> - else - clause of a first. Whatever might be gained in
                      >> attempting to clarify that one - if - statement can be
                      >> weighed against losing the clear one-of-three structure[/color]
                      >
                      > You have to mentally insert the assignment statement and
                      > realize that it isn't a conditional thing.[/color]

                      Maybe it takes the realisation that the - if - statement evaluates an
                      expression and that only a small sub-set of expressions are 'conditional
                      things'. An assignment is just as much an expression as any other, and
                      has a well-defined result. Hence:- a = b = c = d = null; - ( or
                      parenthesised: - a = (b = (c = (d = null))); -)
                      [color=blue]
                      > My thought process is that I have to push the if statement
                      > down in my thinking. Remember the assignment. Then, I have
                      > to recall the if statement. You can see from my formatting
                      > of the code. That I do not have to do this mental activity
                      > because it is written on paper.
                      >
                      > At least for me, I have to do the translation in my head.
                      > It is more complicated for me to understand.[/color]

                      Humans vary considerably in the way they view, model and perceive the
                      world, and there is no doubt in my mind that that is a good thing (there
                      wouldn't be nearly as much invention if everyone's perceptions were
                      identical). Where you see this change as a clarification of the testing
                      logic I see it as an obscuring of the structure of the testing. Which
                      was originally a clear one choice of three and is now two nested choices
                      of two (the outcome is the same but my preference was for the former).

                      <snip>[color=blue]
                      > I reformulated the logic here.
                      >
                      > var node = domCore.getElem entById(label);
                      > if(node)
                      > {
                      > var child;
                      > if('string' == typeof node.innerHTML)
                      > {
                      > node.innerHTML = text.value;
                      > }
                      > else
                      > {
                      > child = node.firstChild ;
                      > if(child)
                      > {
                      > child.data = text.value;
                      > }
                      > else if(document.cre ateTextNode &&
                      > node.appendChil d)
                      > {
                      > node.appendChil d(
                      > document.create TextNode(text.v alue));
                      > }
                      > }
                      > }
                      >
                      > Shows clearly:
                      >
                      > 1) What goes with what
                      > 2) code parrallels the oder the machine will run the code.
                      > You do not have to back scan in the if statment nor do
                      > mental push and pop operations.[/color]

                      While computer languages all exhibit operator precedence in one form or
                      another I don't think there are many programmers who learn (all of) the
                      precedence in any language they work with. Preferring instead to use the
                      appropriate placement of parentheses to make the desired sequence of
                      operations both certain and obvious.

                      I don't see the mental operations involved in comprehending a
                      parenthesised complex mathematical operation as significantly different
                      from that involved in comprehending a logical expression or if
                      expressions that contains assignment expressions (appropriately
                      parenthesised).
                      [color=blue]
                      > 3) avoids the confusion over = and ==[/color]

                      There is no doubt that they are often confused, though mostly by those
                      unfamiliar with javascript (and the many other languages that use the
                      two). And JavaScript 1.2 confused matters even more by considering an
                      assignment directly within an - if - statement's expression as
                      comparison instead. And JSLINT will not put up with it, *unless* the
                      assignment is parenthesised (which also has JavaScript 1.2 treat it as
                      assignment).
                      [color=blue]
                      > 4) Hilights the assignment statement because is valid for
                      > the rest of the code block. It is valid outside the rest
                      > of the if statement. I believe this reason alone is something
                      > you want to hilight. Don't try to hide the assignment in the if
                      > statement where it is easier to miss than if it had it's own
                      > line of code.[/color]

                      While the results of the assignment do indeed stand for the remainder of
                      the execution following it the value assigned to - child - (the fact
                      that it has been assigned a value at all) is only of significance within
                      the one branch of the original code guarded by the - if - statement in
                      which the assignment happened. So it might be argued that placing the
                      assignment in the - if - expression more closely/directly associates it
                      with the code that may employ the result.
                      [color=blue]
                      > You can see from the format of the code that I like to
                      > understand one simple thing at a time then go onto the
                      > next thing.[/color]

                      Fair enough. But consider how some alternative structures might be
                      effected by this type of re-structuring. For example, suppose an
                      initial - if - branch was conditional on two assignments:-

                      var a, b;
                      if(
                      (a = getA()) &&
                      (b = getB())
                      ){
                      // do something with a and b
                      }else{
                      //default action on failure
                      }

                      - once you re-structure it to get the assignments out of the - if -
                      expressions you get something like this:-

                      var b, a = getA();
                      if(a){
                      b = getB();
                      if(b){
                      // do something with a and b
                      }else{
                      // default action on failure
                      }
                      }else{
                      // default action on failure
                      }

                      - in which the - else - code has been doubled-up.

                      Make that three assignments and:-

                      var a, b, c;
                      if(
                      (a = getA()) &&
                      (b = getB()) &&
                      (c = getC())
                      ){
                      // do something with a, b and c
                      }else{
                      // default action on failure
                      }

                      - becomes:-

                      var c, b, a = getA();
                      if(a){
                      b = getB();
                      if(b){
                      c = getC();
                      if(c){
                      // do something with a, b and c.
                      }else{
                      // default action on failure
                      }
                      }else{
                      // default action on failure
                      }
                      }else{
                      // default action on failure
                      }

                      - and it is looking like the - else - code is going to need passing off
                      to a parameterised function call to avoid the repetition (with the
                      consequence that what was previously directly visible code is moved
                      elsewhere, hardly a contribution to clarity).

                      And now if the - else - code itself branches, two branches become six.
                      That looks like escalating complexity to me.

                      There are alternative structures that could avoid repeating the - else -
                      code, such as flagging the success of the nested - if - blocks:-

                      var success = false, c, b, a = getA();
                      if(a){
                      b = getB();
                      if(b){
                      c = getC();
                      if(c){
                      success = true;
                      // do something with a and b
                      }
                      }
                      }
                      if(!success){
                      //default action on failure
                      }

                      - in which success cannot short-circuit the test for success and an
                      extra local variable has been added to the context.

                      However, returning from the function within the innermost - if -
                      branch:-

                      var c, b, a = getA();
                      if(a){
                      b = getB();
                      if(b){
                      c = getC()
                      if(c){
                      // do something with a, b and c
                      return; // avoid the default action by
                      // returning here.
                      }
                      }
                      }
                      // default action on failure (because the function did
                      // not return above)

                      - will short-circuit the default code and remove the necessity to test
                      for success/failure. But now the entire default action code is outside
                      any branching structure and someone missing the return statement might
                      waste time wondering why it is applied on each execution of the
                      function. Indeed there is quite a lot of debate about how and where
                      functions should return, centred around source code clarity, and the
                      above structure illustrates the case for claming that returning from
                      anywhere but the end of a function is less than clear.
                      [color=blue]
                      > In examples to folks who are not as familiar with program,
                      > I believe it is best to code things in an easy to understand
                      > format and avoid coding styles that many programs have noted
                      > as problematic. Look at the code posted to this forum and
                      > note the problems with it.
                      >
                      > Even though you may like using an assignment statement in
                      > an if statement many programmer have found it troublesome.
                      > I assume this must be getting at something. Best to avoid
                      > troublesome situations.[/color]

                      For a novice there probably are advantages in seeing code that is clear
                      on the level of individual expressions. Hopefully I have made a case for
                      suggesting that code written to be clear at that level might be
                      detracting form clarity and simplicity at a higher (structural) level.
                      In learning javascript there must come a point where the individual
                      expressions become second nature and interest moves on to the bigger
                      picture. It wouldn't be fair or reasonable to insist that all code
                      posted to the group catered for a lowest common denominator javascript
                      novice, and under those circumstances a lot of very interesting code
                      would never get the wider public exposure it deserves.

                      Richard.


                      Comment

                      • Michael Winter

                        #12
                        Re: altering text with javascript

                        On Sat, 25 Sep 2004 18:41:40 +0100, Richard Cornford
                        <Richard@litote s.demon.co.uk> wrote:
                        [color=blue][color=green]
                        >> Michael Winter wrote:[/color][/color]

                        [snip]
                        [color=blue][color=green][color=darkred]
                        >>> var e = document.all[n], i = e.length;[/color][/color]
                        > ^
                        > Isn't it a bit premature to be assuming that the - document.all -
                        > collection has returned something at this point?[/color]

                        Oops.

                        This is a new version of old code. Whilst fiddling with the .all section,
                        I must have removed that test without realising.

                        [snip]
                        [color=blue]
                        > var e = (document.all[id] || {} );[/color]

                        I'd probably choose that.
                        [color=blue][color=green][color=darkred]
                        >>> if(isN(i)) {while(i--) {if(e[i].id == n) return e[i];}}
                        >>> else if(e.id == n) {return e;}
                        >>> return null;
                        >>> }
                        >>> : function() {return null;}
                        >>> });
                        >>> })();[/color][/color][/color]

                        function(n) {
                        /* I would use l (L) instead of m, but it won't
                        * show very distinctly in most news readers.
                        */
                        var e = document.all[n] || {}, m = e.length;
                        if(isN(m)) {
                        for(var i = 0;i < m; ++i) {if(e[i].id == n) {return e[i];}}
                        } else if(e.id == n) {return e;}
                        return null;
                        }

                        would probably be better. This way the first, not the last, matching
                        element would be returned. A more expected result. Of course, nothing
                        should really be expected with two or more matches: null is just as
                        correct in the eyes of DOM Core. It's just not very useful.

                        [snip]

                        Mike

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

                        Comment

                        • Grant Wagner

                          #13
                          Re: altering text with javascript

                          Richard Cornford wrote:
                          [color=blue]
                          > var a, b, c;
                          > if(
                          > (a = getA()) &&
                          > (b = getB()) &&
                          > (c = getC())
                          > ){
                          > // do something with a, b and c
                          > }else{
                          > // default action on failure
                          > }
                          >
                          > - becomes:-
                          >
                          > var c, b, a = getA();
                          > if(a){
                          > b = getB();
                          > if(b){
                          > c = getC();
                          > if(c){
                          > // do something with a, b and c.
                          > }else{
                          > // default action on failure
                          > }
                          > }else{
                          > // default action on failure
                          > }
                          > }else{
                          > // default action on failure
                          > }
                          >
                          > - and it is looking like the - else - code is going to need passing off
                          > to a parameterised function call to avoid the repetition (with the
                          > consequence that what was previously directly visible code is moved
                          > elsewhere, hardly a contribution to clarity).[/color]

                          Or:

                          var c, b, a = getA();
                          if(a){
                          b = getB();
                          }
                          if (b) {
                          c = getC();
                          }
                          if (c) {
                          // do something with a, b and c.
                          } else {
                          // default action on failure
                          }

                          Which has the advantage that the tests can be re-ordered, or new tests
                          added, without significantly affecting the underlying logic.

                          It also has as an advantage that if there are many tests to be performed,
                          you do not end up with multiple levels of indentation.

                          Of course, your first code example already provides these advantages.

                          Still, I believe there are places where this modified gauntlet is a good
                          structure, although perhaps not in this particular example.

                          For the OP, a bit more on gauntlets here: <url:
                          http://mindprod.com/jgloss/gauntlet.html />

                          --
                          Grant Wagner <gwagner@agrico reunited.com>
                          comp.lang.javas cript FAQ - http://jibbering.com/faq

                          Comment

                          • Thomas 'PointedEars' Lahn

                            #14
                            Re: altering text with javascript

                            Robert wrote:
                            [color=blue]
                            > 2) There is no need for javascript: in an event handler. Javascript is
                            > assumed in all event handler such as onclick.[/color]

                            No, it is not. In fact, it is only where the default scripting language
                            is J(ava)Script. However, the default scripting language should be defined
                            explicitely when using intrinsic event handler attributes:

                            <meta http-equiv="Content-Script-Type" content="text/javascript">

                            However, especially IE does not care about this declaration; instead,
                            it uses the scripting language of the last script element instead.
                            To workaround this bug, M$ has introduced the abuse of labels in event
                            handler attribute values to specify the scripting language. However,
                            this only works in IE and is a proprietary approach that should not
                            be pursued on the Web.
                            [color=blue]
                            > 3) It is best to put quotes around the javascript code in an event
                            > handler. onClick="myfunc tion();"[/color]

                            More, it is *required* as of SGML:

                            <http://www.w3.org/TR/REC-html32#sgml>
                            <http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2>
                            [color=blue]
                            > 4) It is best to put in the trailing semi-colon ";".[/color]

                            It does not make a real difference whether the trailing semicolon
                            is included in the attribute value or not. In fact, the "overhead"
                            that is saved if the trailing semicolon is omitted is compensated
                            by the then-required built-it automatic semicolon insertion process
                            as specified in ECMAScript.


                            PointedEars
                            --
                            Andre the Giant has some coffee

                            Comment

                            • Jim Ley

                              #15
                              Re: altering text with javascript

                              On Sun, 10 Oct 2004 17:08:45 +0200, Thomas 'PointedEars' Lahn
                              <PointedEars@we b.de> wrote:
                              [color=blue]
                              >Robert wrote:
                              >[color=green]
                              >> 2) There is no need for javascript: in an event handler. Javascript is
                              >> assumed in all event handler such as onclick.[/color]
                              >
                              >No, it is not. In fact, it is only where the default scripting language
                              >is J(ava)Script.[/color]

                              Which is in all user agents that assume a default.
                              [color=blue]
                              > <meta http-equiv="Content-Script-Type" content="text/javascript">[/color]

                              This bogus, and until the HTML WG respond to the comments against it,
                              it doesn't even have much weight of standard, it's certainly not an
                              http-equiv header.
                              [color=blue]
                              >To workaround this bug, M$ has introduced the abuse of labels in event
                              >handler attribute values to specify the scripting language.[/color]

                              This predates the HTML WG's bogosity.
                              [color=blue]
                              > However,
                              >this only works in IE and is a proprietary approach that should not
                              >be pursued on the Web.[/color]

                              Agreed, but it's harmless, as is the meta-equiv of course, but that's
                              just bogus irrelevance.

                              Jim.

                              Comment

                              Working...