getting all the elements of a form

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

    getting all the elements of a form

    If I'm pretty sure there is just one form on the page, can i do this?

    var myForm = document.forms[0];

    If I'm not sure about the form, is it safer to do this?

    if (document.forms[0]) {
    var myForm = document.forms[0];
    // more code here........
    }

    Can I then get the elements array like this?

    var myElements = myForm.elements ;


    ?????????????



    <script type="text/javascript">

    function openInNewWindow String(windowTe xt) {
    window.open(win dowText, 'Show_Form_Subm ission_To_User' ,
    'toolbar=yes,wi dth=200,height= 400,directories =no,status=yes, scrollbars=yes, resizable=yes,m enubar=yes');
    docWindow.focus ();
    return false;
    }

    function postFormSubmiss ionToNewWindow( ) {
    var elementsArrayLe ngth = document.forms[0].length;
    var whatIsBeingSubm itted = '<h1>You just wrote:</h1>';

    for (i=0; i < elementsArrayLe ngth; i++) {
    whatIsBeingSubm itted += document.forms[0].elements[i];
    whatIsBeingSubm itted += '<hr>';
    }

    openInNewWindow String(whatIsBe ingSubmitted);
    }

    </script>
  • RobG

    #2
    Re: getting all the elements of a form

    lawrence wrote:[color=blue]
    > If I'm pretty sure there is just one form on the page, can i do this?[/color]

    You need to be certain as your code will return a reference to the
    first form if it exists.
    [color=blue]
    >
    > var myForm = document.forms[0];[/color]

    Yes.
    [color=blue]
    >
    > If I'm not sure about the form, is it safer to do this?
    >
    > if (document.forms[0]) {
    > var myForm = document.forms[0];
    > // more code here........
    > }
    >[/color]

    Yes, but it's safer to test that the users browser supports
    document.forms before trying to use it:

    if (document.forms && document.forms[0]) {
    ...
    } else {
    // do something else
    // or degrade gracefully
    }
    [color=blue]
    > Can I then get the elements array like this?
    >
    > var myElements = myForm.elements ;[/color]

    Yes. In regard to:
    [color=blue]
    > function postFormSubmiss ionToNewWindow( ) {
    > var elementsArrayLe ngth = document.forms[0].length;[/color]

    Whilst this line works, it is probably better to address the elements
    collection directly using:

    document.forms[0].elements.lengt h

    However, you don't need this variable at all if you modify the
    following line:
    [color=blue]
    > for (i=0; i < elementsArrayLe ngth; i++) {[/color]

    to:

    for (i=0; i < elementsArray.l ength; i++) {

    [...]

    Comment

    • Randy Webb

      #3
      Re: getting all the elements of a form

      RobG wrote:[color=blue]
      > lawrence wrote:
      >[color=green]
      >> If I'm pretty sure there is just one form on the page, can i do this?[/color]
      >
      >
      > You need to be certain as your code will return a reference to the
      > first form if it exists.
      >[color=green]
      >>
      >> var myForm = document.forms[0];[/color]
      >
      >
      > Yes.
      >[color=green]
      >>
      >> If I'm not sure about the form, is it safer to do this?
      >>
      >> if (document.forms[0]) {
      >> var myForm = document.forms[0];
      >> // more code here........
      >> }
      >>[/color]
      >
      > Yes, but it's safer to test that the users browser supports
      > document.forms before trying to use it:
      >
      > if (document.forms && document.forms[0]) {
      > ...
      > } else {
      > // do something else
      > // or degrade gracefully
      > }[/color]

      Is there a browser/UA that does not support document.forms and fails on
      this test:

      if (document.forms[0])

      ?

      --
      Randy
      comp.lang.javas cript FAQ - http://jibbering.com/faq

      Comment

      • RobG

        #4
        Re: getting all the elements of a form

        Randy Webb wrote:[color=blue]
        > RobG wrote:[/color]
        [...][color=blue][color=green]
        >> Yes, but it's safer to test that the users browser supports
        >> document.forms before trying to use it:
        >>
        >> if (document.forms && document.forms[0]) {
        >> ...
        >> } else {
        >> // do something else
        >> // or degrade gracefully
        >> }[/color]
        >
        >
        > Is there a browser/UA that does not support document.forms and fails on
        > this test:
        >
        > if (document.forms[0])
        >[/color]

        My idea was that if a browser does not support document.forms, then
        asking it to evaluate document.forms[0] may return some spurious value
        whereas it should gracefully handle document.forms even if it doesn't
        understand it.

        Or have I totally lost the plot?

        Cheers, Rob.

        Comment

        • Fred Oz

          #5
          Re: getting all the elements of a form

          RobG wrote:
          [...][color=blue]
          >
          > for (i=0; i < elementsArray.l ength; i++) {[/color]

          The OP may want to change that to:

          for (var i=0; i < elementsArray.l ength; i++) {

          unless i really does need to be global.

          Fred.

          Comment

          • Grant Wagner

            #6
            Re: getting all the elements of a form

            RobG wrote:
            [color=blue]
            > Randy Webb wrote:[color=green]
            > > RobG wrote:[/color]
            > [...][color=green][color=darkred]
            > >> Yes, but it's safer to test that the users browser supports
            > >> document.forms before trying to use it:
            > >>
            > >> if (document.forms && document.forms[0]) {
            > >> ...
            > >> } else {
            > >> // do something else
            > >> // or degrade gracefully
            > >> }[/color]
            > >
            > >
            > > Is there a browser/UA that does not support document.forms and fails on
            > > this test:
            > >
            > > if (document.forms[0])
            > >[/color]
            >
            > My idea was that if a browser does not support document.forms, then
            > asking it to evaluate document.forms[0] may return some spurious value
            > whereas it should gracefully handle document.forms even if it doesn't
            > understand it.[/color]

            If a user agent does not understand document.forms in client-side JavaScript,
            then there is no way to handle it at all. You can degrade gracefully and not
            attempt to do anything if you can't access the DOM elements you need to
            access:

            var f = document.forms;
            if (f) {
            f = f['yourFormName'];
            }
            if (f) {
            f = f.elements;
            }
            if (f) {
            if (f['yourInputName']) {
            alert(f['yourInputName'].value);
            }
            }

            Alternatively:

            var f;
            if ((f = document.forms) &&
            (f = f['yourFormName']) &&
            (f = f.elements)) {

            if (f['yourInputName']) {
            alert(f['yourInputName'].value);
            }
            }

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

            Comment

            • lawrence

              #7
              Re: getting all the elements of a form

              Fred Oz <ozfred@iinet.n et.auau> wrote in message news:<4199bcae$ 0$25788$5a62ac2 2@per-qv1-newsreader-01.iinet.net.au >...[color=blue]
              > RobG wrote:
              > [...][color=green]
              > >
              > > for (i=0; i < elementsArray.l ength; i++) {[/color]
              >
              > The OP may want to change that to:
              >
              > for (var i=0; i < elementsArray.l ength; i++) {
              >
              > unless i really does need to be global.[/color]

              Sorry for the idiot question, but why is it global when it is defined
              inside a function? Javascript's scope rules confuse me. How do I make
              it local?

              Comment

              • MyndPhlyp

                #8
                Re: getting all the elements of a form


                "lawrence" <lkrubner@geoci ties.com> wrote in message
                news:da7e68e8.0 411160902.63874 44b@posting.goo gle.com...[color=blue]
                > Fred Oz <ozfred@iinet.n et.auau> wrote in message[/color]
                news:<4199bcae$ 0$25788$5a62ac2 2@per-qv1-newsreader-01.iinet.net.au >...[color=blue][color=green]
                > > RobG wrote:
                > > [...][color=darkred]
                > > >
                > > > for (i=0; i < elementsArray.l ength; i++) {[/color]
                > >
                > > The OP may want to change that to:
                > >
                > > for (var i=0; i < elementsArray.l ength; i++) {
                > >
                > > unless i really does need to be global.[/color]
                >
                > Sorry for the idiot question, but why is it global when it is defined
                > inside a function? Javascript's scope rules confuse me. How do I make
                > it local?[/color]

                <script>
                var i = 0; // global to the document

                function myFunction()
                {
                var j = 0; // global to the function but not the document

                for (var k = 0; k < myThing.length; k++) // global to the for loop but
                not the function or document
                {
                <do some for loop stuff>
                {
                var l = 0; // local to the code block
                }
                }
                }
                </script>

                Where you define the variable determines how global or local it is.


                Comment

                • Grant Wagner

                  #9
                  Re: getting all the elements of a form

                  lawrence wrote:
                  [color=blue]
                  > Fred Oz <ozfred@iinet.n et.auau> wrote in message news:<4199bcae$ 0$25788$5a62ac2 2@per-qv1-newsreader-01.iinet.net.au >...[color=green]
                  > > RobG wrote:
                  > > [...][color=darkred]
                  > > >
                  > > > for (i=0; i < elementsArray.l ength; i++) {[/color]
                  > >
                  > > The OP may want to change that to:
                  > >
                  > > for (var i=0; i < elementsArray.l ength; i++) {
                  > >
                  > > unless i really does need to be global.[/color]
                  >
                  > Sorry for the idiot question, but why is it global when it is defined
                  > inside a function? Javascript's scope rules confuse me. How do I make
                  > it local?[/color]

                  <url: http://docs.sun.com/source/816-6409-...nt.htm#1009822 />

                  As I understand it, variables in JavaScript are properties of an object. If you declare the variable with the "var"
                  keyword, it is a property of the immediate parent object (not code block). If you neglect to include the "var" keyword, it
                  becomes a property of the default global object.

                  var a = 1;
                  function test1() {
                  a = 5; // property of global object
                  }
                  test1();
                  alert(a); // 5

                  var a = 1;
                  function test2() {
                  var a = 5; // property of object referenced by 'test2'
                  }
                  test2();
                  alert(a); // 1

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

                  Comment

                  • Lee

                    #10
                    Re: getting all the elements of a form

                    MyndPhlyp said:
                    [color=blue]
                    ><script>
                    >var i = 0; // global to the document
                    >
                    >function myFunction()
                    >{
                    > var j = 0; // global to the function but not the document
                    >
                    > for (var k = 0; k < myThing.length; k++) // global to the for loop but
                    >not the function or document
                    > {
                    > <do some for loop stuff>
                    > {
                    > var l = 0; // local to the code block
                    > }
                    > }
                    >}
                    ></script>
                    >
                    >Where you define the variable determines how global or local it is.[/color]

                    Your k and l will actually be local to the function,
                    not the loop or block as in many other languages.

                    Comment

                    • Michael Winter

                      #11
                      Re: getting all the elements of a form

                      On 16 Nov 2004 09:02:07 -0800, lawrence <lkrubner@geoci ties.com> wrote:

                      [snip]
                      [color=blue]
                      > Sorry for the idiot question, but why is it global when it is defined
                      > inside a function? Javascript's scope rules confuse me.[/color]

                      The scope rules are similar to other languages, with one major exception:
                      there's no block scope.

                      At a conceptual level, there are three levels of scope: global, object,
                      and local.

                      1) Global variables and functions can be accessed by any script within a
                      document. You declare global variable with

                      var identifier;

                      outside any function. Similarly, defining a function outside any other
                      function

                      function myFunction() {
                      }

                      will cause myFunction to be global. Finally, if you assign a value to a
                      previously undefined identifier

                      unique = value;

                      it is created global. This is what happened with 'i' in your code. It
                      wasn't defined anywhere, so it would become global.

                      2) By "object" scope, I'm refering to the properties of an object. I
                      shouldn't need to explain that any further.

                      3) Local variables are made local through use of the var keyword. When it
                      is used within a function, that variable is local to that function.

                      function myFunction() {
                      var myVariable;
                      }

                      /* myVariable doesn't exist here. */

                      The details of variable scope - what goes on "under the hood" - is really
                      quite different, but I'll leave that and allow you to digest the
                      explanation above.
                      [color=blue]
                      > How do I make it local?[/color]

                      Fred did in his post: declare the variable using the var keyword within a
                      function.

                      Mike

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

                      Comment

                      • Richard Cornford

                        #12
                        Re: getting all the elements of a form

                        MyndPhlyp wrote:[color=blue]
                        > lawrence wrote:[/color]
                        <snip>[color=blue][color=green]
                        >> Sorry for the idiot question, but why is it global when it
                        >> is defined inside a function? Javascript's scope rules
                        >> confuse me. How do I make it local?[/color]
                        > <script>
                        > var i = 0; // global to the document
                        >
                        > function myFunction()
                        > {
                        > var j = 0; // global to the function but not the document
                        >
                        > for (var k = 0; k < myThing.length; k++) // global to the
                        > for loop but not the function or document[/color]

                        That isn't true. Languages such as Java are block scoped but
                        javascript/ECMAScript is not. All variables declared within a function
                        using the - var - keyword are scoped to the (whole) function (including
                        any inner functions it may have).

                        <snip>[color=blue]
                        > Where you define the variable determines how global or local
                        > it is.[/color]

                        True, but in javascript that scopeing is lexical and at function
                        intervals.

                        Richard.


                        Comment

                        • lawrence

                          #13
                          Re: getting all the elements of a form

                          I've implemented the function which you can see below, and now when I
                          hit post on a form, I've started gettting this error in the new
                          window, and nothing input on the first page:
                          [color=blue][color=green][color=darkred]
                          >>>>>>>>>>>>>>> >>[/color][/color][/color]
                          Not Found
                          The requested URL /<h1>You just wrote:</h1>[object
                          HTMLInputElemen t]<hr>[object HTMLInputElemen t]<hr>[object
                          HTMLInputElemen t]<hr>[object HTMLInputElemen t]<hr> was not found on
                          this server.
                          Additionally, a 404 Not Found error was encountered while trying to
                          use an ErrorDocument to handle the request.[color=blue][color=green][color=darkred]
                          >>>>>>>>>>>>>>> >>[/color][/color][/color]


                          Is this because of the javascript, or should I look somewhere else for
                          the problem? Does the javascript somehow suck the info out of the form
                          when the form is input? That was not my intention. I want all the form
                          info to be input to my PHP script. I only wanted to show the user what
                          they'd just input, using Javascript.





                          lkrubner@geocit ies.com (lawrence) wrote in message news:<da7e68e8. 0411151941.4299 5d96@posting.go ogle.com>...[color=blue]
                          > If I'm pretty sure there is just one form on the page, can i do this?
                          >
                          > var myForm = document.forms[0];
                          >
                          > If I'm not sure about the form, is it safer to do this?
                          >
                          > if (document.forms[0]) {
                          > var myForm = document.forms[0];
                          > // more code here........
                          > }
                          >
                          > Can I then get the elements array like this?
                          >
                          > var myElements = myForm.elements ;
                          >
                          >
                          > ?????????????
                          >
                          >
                          >
                          > <script type="text/javascript">
                          >
                          > function openInNewWindow String(windowTe xt) {
                          > window.open(win dowText, 'Show_Form_Subm ission_To_User' ,
                          > 'toolbar=yes,wi dth=200,height= 400,directories =no,status=yes, scrollbars=yes, resizable=yes,m enubar=yes');
                          > docWindow.focus ();
                          > return false;
                          > }
                          >
                          > function postFormSubmiss ionToNewWindow( ) {
                          > var elementsArrayLe ngth = document.forms[0].length;
                          > var whatIsBeingSubm itted = '<h1>You just wrote:</h1>';
                          >
                          > for (i=0; i < elementsArrayLe ngth; i++) {
                          > whatIsBeingSubm itted += document.forms[0].elements[i];
                          > whatIsBeingSubm itted += '<hr>';
                          > }
                          >
                          > openInNewWindow String(whatIsBe ingSubmitted);
                          > }
                          >
                          > </script>[/color]

                          Comment

                          • Michael Winter

                            #14
                            Re: getting all the elements of a form

                            On 18 Nov 2004 00:19:29 -0800, lawrence <lkrubner@geoci ties.com> wrote:

                            [snip]
                            [color=blue]
                            > Is this because of the javascript,[/color]

                            Yes, specifically

                            window.open(win dowText,

                            The first argument to window.open is *always* a URL. What the browser is
                            attempting is to open a network resource using the string you generate.

                            Obviously, this isn't your intent. What you need to do is use the
                            javascript: scheme. This will instruct the browser to evaluate the
                            following text as if it were Javascript. You then should pass a string
                            literal which the browser will display.

                            function openInNewWindow String(windowTe xt) {
                            window.open('ja vascript:"'
                            + windowText.repl ace(/\"/g, '\\"') + '"',
                            'userSubmission ',
                            'width=200,heig ht=400,status,s crollbars,resiz able,toolbar');

                            Notice that I alter the string. If double quotes were present in the
                            string, it would produce a syntax error. Replacing " with \" removes that
                            problem. Also notice the slightly shorter, but equivalent, feature string.

                            [snip]
                            [color=blue][color=green]
                            >> function postFormSubmiss ionToNewWindow( ) {[/color][/color]

                            Here's a replacement:

                            var elem = document.forms[0].elements,
                            temp = ['<h1>You just wrote:<\/h1>'];

                            for(var i = 0, n = elem.length; i < n; ++i) {
                            temp[temp.length] = elem[i].name;
                            temp[temp.length] = ': ';
                            temp[temp.length] = elem[i].value;
                            temp[temp.length] = '<hr>';
                            }
                            openInNewWindow String(temp.joi n(''));

                            There are two major changes here:

                            1) The items are added to an array, then concatenated at the end.

                            The idea is that the native code that executes the join method is faster
                            than doing a large number of += concatenations.

                            2) I've output the names of each element, followed by their values.

                            If you look at the error message you posted, you'll see things like
                            [object HTMLInputElemen t]. That is what an INPUT element produces when you
                            call its toString method. Not very useful, is it.

                            Just outputting the names and values is a very simplistic approach, but
                            fine if you just have some INPUT (text) controls. If you start
                            incorporating the presence of SELECT elements with the multiple attribute
                            set, or disabled controls, you'll have to do a lot more work.

                            Hope that helps,
                            Mike


                            In future, please don't top-post. Even to your own messages.

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

                            Comment

                            • lawrence

                              #15
                              Re: getting all the elements of a form

                              "Michael Winter" <M.Winter@bluey onder.co.invali d> wrote in message news:<opshnlzwk px13kvk@atlanti s>...[color=blue]
                              > On 18 Nov 2004 00:19:29 -0800, lawrence <lkrubner@geoci ties.com> wrote:
                              >
                              > Just outputting the names and values is a very simplistic approach, but
                              > fine if you just have some INPUT (text) controls. If you start
                              > incorporating the presence of SELECT elements with the multiple attribute
                              > set, or disabled controls, you'll have to do a lot more work.[/color]

                              Thank you. I've been thinking about some of the complaints that
                              Jonathan Delacour had about the state of web writing tools:
                              http://weblog.delacour.net/archives/...iting_tool.php.

                              As he points out, this is a problem for the makers of web browsers to
                              solve. It can't be solved with PHP or Javascript. However, a few of
                              the worst problems can be slightly ameliorated with Javascript. One
                              problem that trips people up is when they write a long entry (in a
                              textarea in a form on a page that will then be submitted to a PHP,
                              Perl, or Python script) then hit the submit button, only to lose all
                              their work because while they were writing they either lost their
                              internet connection or their session timed out. I know I've lost work
                              this way. At a minimum, I've been thinking, the browser can take all
                              the form data and replicate it somewhere, perhaps in another window,
                              so that all your data won't get lost if you hit the submit and it
                              turns out you no longer have an internet connection.



                              [color=blue][color=green]
                              > > Is this because of the javascript,[/color]
                              >
                              > Yes, specifically
                              >
                              > window.open(win dowText,
                              >
                              > The first argument to window.open is *always* a URL. What the browser is
                              > attempting is to open a network resource using the string you generate.
                              >
                              > Obviously, this isn't your intent. What you need to do is use the
                              > javascript: scheme. This will instruct the browser to evaluate the
                              > following text as if it were Javascript. You then should pass a string
                              > literal which the browser will display.[/color]

                              I'll implement this. Does the form data on the parent page still get
                              submitted to the server in the normal way?

                              Comment

                              Working...