empty string

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

    empty string

    Hi
    I have been busy going through the last weeks postings in an attempt to
    absorb javascript syntax (I guess it's not possible to just absorb this
    stuff in a passive way - I'm getting way out of my depth with most of the
    posts, I will buy a good book and take some online tutorials)

    Anyway, I think I almost understand one of Mr Nielsen's posts on form
    validation. It all centers around whether I am interpreting an empty string
    correctly - see below


    Mr Nielsen states:

    To validate a function, always use this way to call the validation function:
    ---
    <form ... onsubmit="retur n validate(this)" >
    ---
    The function itself is then:
    ---
    function validate(form) {
    var cashEmpty = form.elements['cash'].value == "";
    var invoiceEmpty = form.elements['invoice'].value == "";
    if (cashEmpty && invoiceEmpty) {
    alert("Fill in at least one of the fields: Cash or Invoice.");
    return false;
    }
    return true;
    }



    =============== =============== =============== =============== ==============

    I think the code above is saying - if the value of the form control named
    'cash' has had nothing entered into it by the user, then assign a value of
    'zero length string' to the variable called cashEmpty. A zero sized string
    is not a null value, so effectively, the empty variable 'cashEmpty' is
    flagging 'true' in the if conditional because it has a value (which is the
    value 'zero sized string'). Same story for the other form element.

    I think I may be making this up. Does javascript see something that is
    equivalent of "" as having a value?

    Thanks for any reply
    David




  • Richard Cornford

    #2
    Re: empty string

    "David Graham" <david.graham18 @ntlworld.com> wrote in message
    news:HRixb.14$h 84.3@newsfep1-gui.server.ntli .net...
    <snip>[color=blue]
    >| var cashEmpty = form.elements['cash'].value == "";[/color]
    <snip>[color=blue]
    >I think the code above is saying - if the value of the form
    >control named 'cash' has had nothing entered into it by the
    >user, then assign a value of 'zero length string' to the
    >variable called cashEmpty. A zero sized string is not a null
    >value, so effectively, the empty variable 'cashEmpty' is
    >flagging 'true' in the if conditional because it has a value
    >(which is the value 'zero sized string'). Same story for the
    >other form element.[/color]

    No, you have misunderstood. Earlier in the week you may nave noticed
    Evertjan commenting on my parenthesising sub-expressions, maybe Lasse
    should have done the same to the above. Parenthesising the expression
    produces:-

    var cashEmpty = (form.elements['cash'].value == "");

    - where the result of the parenthesised expression is assigned to the
    value of the local variable. The parenthesised expression is a
    comparison and a comparison produces a *boolean* true or false result.
    So it is that boolean value that is assigned to the local variable. true
    if the form element value equals - "" -(in the type-converting
    comparison sense[1]) or false if it does not. Parentheses are not
    required in the source code because operator precedence would require
    that the comparison operation happen prior to the assignment operation
    (else it would be uncertain which value to assign to the variable).

    Richard.

    [1] In addition to the type-converting - == - equality operator, which
    would assert that numeric zero, undefined, null and boolean false also
    equalled an empty string, recent JavaScript versions have a strict
    equality operator - === - which would only believe that an empty string
    equalled an empty string. In the above example it doesn't matter much if
    the - == - equality operator is used because the value property of form
    elements is always a string and the only string that will equal an empty
    string is and empty string. Browsers such as IE 4 do not implement the
    strict equality operator and consider it a syntax error, but there aren’
    t many of those left now.


    Comment

    • Lasse Reichstein Nielsen

      #3
      Re: empty string

      "Richard Cornford" <Richard@litote s.demon.co.uk> writes:
      [color=blue]
      > No, you have misunderstood. Earlier in the week you may nave noticed
      > Evertjan commenting on my parenthesising sub-expressions, maybe Lasse
      > should have done the same to the above.[/color]

      Acknowledged.

      /L :)
      --
      Lasse Reichstein Nielsen - lrn@hotpop.com
      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
      'Faith without judgement merely degrades the spirit divine.'

      Comment

      • David Graham

        #4
        Re: empty string


        "Richard Cornford" <Richard@litote s.demon.co.uk> wrote in message
        news:bq4fjh$qh6 $1$8302bc10@new s.demon.co.uk.. .[color=blue]
        > "David Graham" <david.graham18 @ntlworld.com> wrote in message
        > news:HRixb.14$h 84.3@newsfep1-gui.server.ntli .net...
        > <snip>[color=green]
        > >| var cashEmpty = form.elements['cash'].value == "";[/color]
        > <snip>[color=green]
        > >I think the code above is saying - if the value of the form
        > >control named 'cash' has had nothing entered into it by the
        > >user, then assign a value of 'zero length string' to the
        > >variable called cashEmpty. A zero sized string is not a null
        > >value, so effectively, the empty variable 'cashEmpty' is
        > >flagging 'true' in the if conditional because it has a value
        > >(which is the value 'zero sized string'). Same story for the
        > >other form element.[/color]
        >
        > No, you have misunderstood. Earlier in the week you may nave noticed
        > Evertjan commenting on my parenthesising sub-expressions, maybe Lasse
        > should have done the same to the above. Parenthesising the expression
        > produces:-
        >
        > var cashEmpty = (form.elements['cash'].value == "");
        >
        > - where the result of the parenthesised expression is assigned to the
        > value of the local variable. The parenthesised expression is a
        > comparison and a comparison produces a *boolean* true or false result.
        > So it is that boolean value that is assigned to the local variable. true
        > if the form element value equals - "" -(in the type-converting
        > comparison sense[1]) or false if it does not. Parentheses are not
        > required in the source code because operator precedence would require
        > that the comparison operation happen prior to the assignment operation
        > (else it would be uncertain which value to assign to the variable).
        >
        > Richard.
        >
        > [1] In addition to the type-converting - == - equality operator, which
        > would assert that numeric zero, undefined, null and boolean false also
        > equalled an empty string, recent JavaScript versions have a strict
        > equality operator - === - which would only believe that an empty string
        > equalled an empty string. In the above example it doesn't matter much if
        > the - == - equality operator is used because the value property of form
        > elements is always a string and the only string that will equal an empty
        > string is and empty string. Browsers such as IE 4 do not implement the
        > strict equality operator and consider it a syntax error, but there aren'
        > t many of those left now.
        >[/color]
        Thanks for the explanation - I was thinking way off here, I'm really glad
        you posted this.

        David


        Comment

        • David Graham

          #5
          Re: empty string


          "Richard Cornford" <Richard@litote s.demon.co.uk> wrote in message
          news:bq4fjh$qh6 $1$8302bc10@new s.demon.co.uk.. .[color=blue]
          > "David Graham" <david.graham18 @ntlworld.com> wrote in message
          > news:HRixb.14$h 84.3@newsfep1-gui.server.ntli .net...
          > <snip>[color=green]
          > >| var cashEmpty = form.elements['cash'].value == "";[/color]
          > <snip>[color=green]
          > >I think the code above is saying - if the value of the form
          > >control named 'cash' has had nothing entered into it by the
          > >user, then assign a value of 'zero length string' to the
          > >variable called cashEmpty. A zero sized string is not a null
          > >value, so effectively, the empty variable 'cashEmpty' is
          > >flagging 'true' in the if conditional because it has a value
          > >(which is the value 'zero sized string'). Same story for the
          > >other form element.[/color]
          >
          > No, you have misunderstood. Earlier in the week you may nave noticed
          > Evertjan commenting on my parenthesising sub-expressions, maybe Lasse
          > should have done the same to the above. Parenthesising the expression
          > produces:-
          >
          > var cashEmpty = (form.elements['cash'].value == "");
          >[/color]
          Parentheses are not[color=blue]
          > required in the source code because operator precedence would require
          > that the comparison operation happen prior to the assignment operation
          > (else it would be uncertain which value to assign to the variable).
          >[/color]
          Just a quick follow up. Is it best practice to add the parentheses even when
          they are not required. I can think that there is some gain to doing this as
          a novice such as myself could probably follow the code more easily - or is
          it bad to add redundant code full-stop. I am trying to learn good habits and
          avoid bad habits at this early stage of learning.
          David


          Comment

          • David Graham

            #6
            Re: empty string


            "Richard Cornford" <Richard@litote s.demon.co.uk> wrote in message
            news:bq4fjh$qh6 $1$8302bc10@new s.demon.co.uk.. .[color=blue]
            > "David Graham" <david.graham18 @ntlworld.com> wrote in message
            > news:HRixb.14$h 84.3@newsfep1-gui.server.ntli .net...
            > <snip>[color=green]
            > >| var cashEmpty = form.elements['cash'].value == "";[/color]
            > <snip>[color=green]
            > >I think the code above is saying - if the value of the form
            > >control named 'cash' has had nothing entered into it by the
            > >user, then assign a value of 'zero length string' to the
            > >variable called cashEmpty. A zero sized string is not a null
            > >value, so effectively, the empty variable 'cashEmpty' is
            > >flagging 'true' in the if conditional because it has a value
            > >(which is the value 'zero sized string'). Same story for the
            > >other form element.[/color]
            >
            > No, you have misunderstood. Earlier in the week you may nave noticed
            > Evertjan commenting on my parenthesising sub-expressions, maybe Lasse
            > should have done the same to the above. Parenthesising the expression
            > produces:-
            >
            > var cashEmpty = (form.elements['cash'].value == "");
            >[/color]

            It has been suggested in this newsgroup that

            var cashEmpty = (document.forms['form'].elements['cash'].value == "");

            Is a more proper way to refer to the form - presumably, the form would be
            named like this

            <form name="form" ...........

            Is this best practice?

            Would the call to the function and the parameter name remain the same i.e.
            would the following lines remain as they are now?

            <form ... onsubmit="retur n validate(this)" >
            ---
            The function itself is then:
            ---
            function validate(form) {


            Again - thanks for any help
            David




            [color=blue]
            > - where the result of the parenthesised expression is assigned to the
            > value of the local variable. The parenthesised expression is a
            > comparison and a comparison produces a *boolean* true or false result.
            > So it is that boolean value that is assigned to the local variable. true
            > if the form element value equals - "" -(in the type-converting
            > comparison sense[1]) or false if it does not. Parentheses are not
            > required in the source code because operator precedence would require
            > that the comparison operation happen prior to the assignment operation
            > (else it would be uncertain which value to assign to the variable).
            >
            > Richard.
            >
            > [1] In addition to the type-converting - == - equality operator, which
            > would assert that numeric zero, undefined, null and boolean false also
            > equalled an empty string, recent JavaScript versions have a strict
            > equality operator - === - which would only believe that an empty string
            > equalled an empty string. In the above example it doesn't matter much if
            > the - == - equality operator is used because the value property of form
            > elements is always a string and the only string that will equal an empty
            > string is and empty string. Browsers such as IE 4 do not implement the
            > strict equality operator and consider it a syntax error, but there aren'
            > t many of those left now.
            >
            >[/color]


            Comment

            • Lasse Reichstein Nielsen

              #7
              Re: empty string

              "David Graham" <david.graham18 @ntlworld.com> writes:
              [color=blue]
              > Just a quick follow up. Is it best practice to add the parentheses even when
              > they are not required.[/color]

              Unneeded parentheses are there only to improve readability. Whether you need
              them or not depends entirely on who will read it.
              I would never us parentheses in a "chain assignment" like
              foo = (bar = (baz = 42))
              *if* I were writing to people used to a C-like language. It confuzes me :)
              But to people who are used to, e.g., BASIC, which some readers of this
              group is, it is probably prudent. (I would probably add a note saying
              that assignment associates to the right, so the parentheses are not
              necessary, so they can learn the traditional way of writing it.).
              [color=blue]
              > I can think that there is some gain to doing this as a novice such
              > as myself could probably follow the code more easily - or is it bad
              > to add redundant code full-stop.[/color]

              It's not bad or redundant, just a little extra verbose.
              [color=blue]
              > I am trying to learn good habits and avoid bad habits at this early
              > stage of learning.[/color]

              Good choice!

              I would say: Set the parentheses. Then think about which you can remove.
              When you become more fluent, you can do that while you write :)

              /L
              --
              Lasse Reichstein Nielsen - lrn@hotpop.com
              DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
              'Faith without judgement merely degrades the spirit divine.'

              Comment

              • Lasse Reichstein Nielsen

                #8
                Re: empty string

                "David Graham" <david.graham18 @ntlworld.com> writes:
                [color=blue][color=green]
                >> var cashEmpty = (form.elements['cash'].value == "");[/color][/color]
                [color=blue]
                > It has been suggested in this newsgroup that
                >
                > var cashEmpty = (document.forms['form'].elements['cash'].value == "");
                >
                > Is a more proper way to refer to the form - presumably, the form would be
                > named like this
                >
                > <form name="form" ...........
                >
                > Is this best practice?[/color]

                Using
                document.forms['form']
                to refer to the form named "form" is infinityle better than just writing
                form
                (i.e., use the name as a global variable). Among other things, it actually
                works in Mozilla.

                The document.forms collection is part of the W3C DOM specification, so any
                new browser will most likely support it. Any other way to refer to a form
                (from scratch) will not have the same official endorsement. Still, just
                writing document.form (i.e., the form directly as a property of the document
                object) will probably be supported by browsers for a long time.

                Now, I said "from scratch". If you already have a reference to the
                form, then there is no need to go through hoops to get to it. This is
                the case here: the name "form" is not used as a global variable. It is
                a local variable, the argument of a function:
                function (form) { ... }

                So, in this case,
                var cashEmpty = (form.elements['cash'].value == "");
                is the recommended way of writing it. It's only because *we* have made
                the variable "form" point to the form. We don't assume that the browser
                has done it for us - that would be wrong.
                [color=blue]
                > Would the call to the function and the parameter name remain the same i.e.
                > would the following lines remain as they are now?
                >
                > <form ... onsubmit="retur n validate(this)" >[/color]

                If you find the form from scratch, you don't need the argument to validate.
                It is much easier just sending the form reference as an argument, though.
                [color=blue]
                > ---
                > The function itself is then:
                > ---
                > function validate(form) {[/color]

                Exactly. :)

                /L
                --
                Lasse Reichstein Nielsen - lrn@hotpop.com
                DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                'Faith without judgement merely degrades the spirit divine.'

                Comment

                • David Graham

                  #9
                  Re: empty string

                  Thanks for that reply. I have a lot of learning to do. I inderstood
                  everything you said, except

                  [color=blue]
                  > <form ... onsubmit="retur n validate(this)" >[/color]


                  If you find the form from scratch, you don't need the argument to validate.
                  It is much easier just sending the form reference as an argument, though.



                  The two lines above don't really mean much to me - yet!

                  Any chance of having another go at rephrasing that (taking into
                  consideration that this is a bit like teaching my dog the theory of
                  relativity)

                  thanks
                  David




                  Comment

                  • Michael Winter

                    #10
                    Re: empty string

                    David Graham wrote on 27 Nov 2003:
                    [color=blue]
                    > Thanks for that reply. I have a lot of learning to do. I
                    > inderstood everything you said, except
                    >[color=green]
                    >> <form ... onsubmit="retur n validate(this)" >
                    >>
                    >> If you find the form from scratch, you don't need the argument
                    >> to validate. It is much easier just sending the form reference
                    >> as an argument, though.[/color]
                    >
                    > The two lines above don't really mean much to me - yet!
                    >
                    > Any chance of having another go at rephrasing that (taking into
                    > consideration that this is a bit like teaching my dog the theory
                    > of relativity)[/color]

                    Consider this function:

                    function validateForm() {
                    var theForm = document.forms['myForm'];

                    if ( 'someValue' == theForm.element s['someElement'].value ) {
                    // do some stuff
                    }
                    }

                    ....and it's form:

                    <FORM action="..." method="..." name="myForm"
                    onsubmit="retur n validateForm()" >
                    ....
                    </FORM>

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

                    Now compare it to this function:

                    function validateForm( theForm ) {
                    if ( 'someValue' == theForm.element s['someElement'].value ) {
                    // do some stuff
                    }
                    }

                    ....and it's form:

                    <FORM action="..." method="..." name="myForm"
                    onsubmit="retur n validateForm( this )">
                    ....
                    </FORM>


                    With the first snippet, nothing is passed to the function. It has to
                    create its own reference, then use that to analyse the form.

                    With the second snippet, the reference to the form is passed (using
                    the keyword, this) during the call, removing the need to perform the
                    lookup that the first function required.

                    It's not much of a difference in this example, but it shows that
                    passing the reference means less typing at the very least. It can
                    prevent trivial errors, such as mistyping the form name, and if you
                    changed the name of the form, the second function doesn't need to be
                    altered in any way. There might be additional benefits - I'm just not
                    seeming them at the moment.

                    That help?

                    Mike

                    --
                    Michael Winter
                    M.Winter@blueyo nder.co.uk.invalid (remove ".invalid" to reply)

                    Comment

                    • Lasse Reichstein Nielsen

                      #11
                      Re: empty string

                      "David Graham" <david.graham18 @ntlworld.com> writes:
                      [color=blue][color=green]
                      >> <form ... onsubmit="retur n validate(this)" >[/color][/color]
                      [color=blue]
                      > Any chance of having another go at rephrasing that (taking into
                      > consideration that this is a bit like teaching my dog the theory of
                      > relativity)[/color]

                      The onsubmit handler contains the following code
                      return validate(this);
                      It calls the function "validate" with one argument. The code is
                      evaluated as a method of the form element, so "this" refers directly
                      to the form. So, the argument is a reference to the form.

                      At the receiving end, the function is defined as:
                      function validate(form) { ... }
                      That means that the local variable "form" will refer directly
                      to the form. There is no need to find the form using document.forms,
                      because you already have it. Using just
                      form.elements['inputName']
                      is the simplest way to access the input element.

                      If you *don't* have easy access to the form, you need to use the full
                      address of the element:
                      document.forms['formId'].elements['inputName']

                      The thing that is incorrect is writing:
                      formId.inputNam e (broken in Mozilla)
                      or
                      document.formId .inputName (works in the browsers I have tested, but is
                      not part of any standard)

                      /L
                      /L
                      --
                      Lasse Reichstein Nielsen - lrn@hotpop.com
                      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                      'Faith without judgement merely degrades the spirit divine.'

                      Comment

                      Working...