Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Accessing Form Objects By Name Is Always "Undefined"

    My HTML is loaded with IDs, because getElementById seems to be the only way to get an element, that actually works.

    Theoretically, you're supposed to be able to go to an object using names. For example I have a form named "StoreFrontContact" and an input field named "Phone". So I should be able to access the input field value with:
    Code:
    document.StoreFrontContact.Phone.value
    but I get the error:
    Code:
    document.StoreFrontContact.Phone is undefined
    Even though there is a form named "StoreFrontContact", with a text field named "Phone".

    Does every level count? So if the form is in a div and the input is in a fieldset, do I need to give those elements names too? That seems just as bad as giving every input field an id.

  • #2
    Banned
    Join Date
    May 2005
    Location
    Midwest, U.S.
    Posts
    118
    Thanks
    1
    Thanked 26 Times in 23 Posts
    Code:
    var nPhone =   document.forms['StoreFrontContact']['Phone'].value

  • #3
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by lightnb View Post
    My HTML is loaded with IDs, because getElementById seems to be the only way to get an element, that actually works.

    Theoretically, you're supposed to be able to go to an object using names. For example I have a form named "StoreFrontContact" and an input field named "Phone". So I should be able to access the input field value with:
    Code:
    document.StoreFrontContact.Phone.value
    but I get the error:
    Code:
    document.StoreFrontContact.Phone is undefined
    Even though there is a form named "StoreFrontContact", with a text field named "Phone".

    Does every level count? So if the form is in a div and the input is in a fieldset, do I need to give those elements names too? That seems just as bad as giving every input field an id.
    could something else in your case but check how name attribute is spelled. javascript is case sensitive so Phone is different then phone.
    Anyway there are another two ways of accessing forms:

    http://www.javascriptkit.com/jsref/form.shtml

    I hope this help.

    best regards

  • #4
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I'm now trying:

    Code:
    var nPhone = document.forms['StoreFrontContact']['Phone'].value;
    and getting:

    Code:
    document.forms.StoreFrontContact.Phone is undefined
    I double-checked the spelling, and they're the same, include case.

    So forms is an associative array? I thougth JavaScript didn't support those?

    And why the 'n' before 'Phone' in the variable name?

    Thanks!

  • #5
    Banned
    Join Date
    May 2005
    Location
    Midwest, U.S.
    Posts
    118
    Thanks
    1
    Thanked 26 Times in 23 Posts
    Are you waiting until the document loads?

    Place in the Head:
    Code:
    <script type="text/javascript">
    
         onload = function(){alert(document.forms['StoreFrontContact']['Phone'].value)}
    
    </script>
    You may address a form either by its ordinal number or name. If you have only one form on the page:

    Code:
     document.forms[0]
    is the same as,

    Code:
     document.forms['StoreFrontContact']
    The "n" is my system of notation, so that I don't use a variable name that is the same as a form field name.

  • #6
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    The onload code gives the same error:
    Code:
    document.forms.StoreFrontContact.Phone is undefined
    I don't think it's a loading order problem: my call to the form element resides in a validation function that only runs when the user clicks the "save" button.

    Unless I'm missing something stupidly obvious?

  • #7
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by lightnb View Post
    The onload code gives the same error:
    Code:
    document.forms.StoreFrontContact.Phone is undefined
    I don't think it's a loading order problem: my call to the form element resides in a validation function that only runs when the user clicks the "save" button.

    Unless I'm missing something stupidly obvious?
    can you post a link to that page?

    best regards

  • #8
    Banned
    Join Date
    May 2005
    Location
    Midwest, U.S.
    Posts
    118
    Thanks
    1
    Thanked 26 Times in 23 Posts
    The following works, for both onload, and upon submit:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Any Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    	function validate(nForm){
    
    		alert(nForm['Phone'].value);
    		return false;
    	}
    
    	onload = function()
    		{
    		 alert(document.forms[0]['Phone'].value);
    		 alert(document.forms['StoreFrontContact']['Phone'].value);
    		}
    	
    </script>
    <style type="text/css">
    
    	 body {background-color: #eae3c6; margin-top: 60px;}
    	 form {width: 620px; margin: auto; font-family: times; font-size: 12pt;}
    	 fieldset {width: 620px; background-color: #f0fff0; border: 1px solid #87ceeb;}
    	 legend {font-family: times; font-size: 14pt; color: #00008b; background-color: #87ceeb; padding-left: 3px; padding-right: 3px; margin-bottom: 5px;}
    	.submitBtn {font-family: tahoma; font-size: 10pt; display: block; margin-left: auto; margin-right: auto; margin-top: 5px; margin-bottom: 5px;}
    
    </style>
    </head>
    	<body>
    		<form name="StoreFrontContact" action="" method="post" onsubmit="return validate(this)">
    		   <fieldset>
    			<legend>Form</legend>
    				<input type="text" name="Phone" value="hello">
    				<input type="submit" name="submit" value="Submit" class="submitBtn">
    		   </fieldset>
    		</form>
    	</body>
    </html>

  • #9
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I ran the page through the W3C Validator, and got this error:

    Code:
    Line 89, Column 14: there is no attribute "name".
    <form name="StoreFrontContact">
    I was using the XHTML Strict doctype, which apparently doesn't support the "name" attribute. I switched to "transitional" and now the JavaScript works.

    Odd...

    Thanks guys!

    I still don't quite get the tree traversal stuff though... Where you can access elements like an array with brackets [] or using the period. Why do you use one vs the other? And how does it know what's a variable, whats an element name, and what's a function?

    And last, how do you call a variable function in javascript? In PHP, you just add parentheses to the end of the variable, and it executes a function with the name of the variable's value, like:

    PHP Code:
    $MyFunction 'FunctionName';
    $Result $MyFunction(); 
    Thanks!

  • #10
    Banned
    Join Date
    May 2005
    Location
    Midwest, U.S.
    Posts
    118
    Thanks
    1
    Thanked 26 Times in 23 Posts
    I use JavaScript Object Notation, because I prefer it -- no other reason. I just don't like the dot notation.

    And yes, JavaScript supports associative arrays. I use them for dependent select lists. The "value" of the selection from the first list, references the array of options for the second list:

    Code:
    var categories = [];
      categories['holidays'] = ["Christmas,New Year,Valentine's Day"];
    In forms, many times, several elements, like checkboxes or radio buttons will have the same name, e.g.: name="someBoxes[]"

    To step through them, you can use:

    Code:
    document.getElementsByName('someBoxes[]'),
    which will return an array.

    There is also,

    Code:
     document.getElementsByTagName('td')
    which also returns an array.

    Global variables in JavaScript are declared outside of functions, declared inside they are local to that function, but can be passed to another function as an argument, if you call that function within the first function.

    Any function can access a global variable.


    Code:
            function first(){
                var myVar = "hello";
                secondFunction(myVar);
            }
    I believe there is a "new Function()" function in JavaScript to create a function from a variable name, but I've never used it and wouldn't want to. I'm not sure if it's generally supported. I can't think of a reason to create a function from a variable name.

    But, you can use a variable to call an existing function, like this:

    Code:
    var myFunction = "init";
    
           window[myFunction]();

    that will call the "init" function.


    Anyway, that's my two-cents.

  • Users who have thanked Cranford for this post:

    lightnb (09-03-2008)

  • #11
    Regular Coder Samhain13's Avatar
    Join Date
    Aug 2008
    Location
    Pilipinas
    Posts
    169
    Thanks
    4
    Thanked 18 Times in 18 Posts
    I was using the XHTML Strict doctype, which apparently doesn't support the "name" attribute. I switched to "transitional" and now the JavaScript works.
    Name attributes can only be used if an ID attribute is also present (I think).

    Why not just use IDs in your form elements, along with the NAMEs?

    Code:
    document.getElementById('myInput').value ;
    is more convenient to code. That way, you don't have to go through all the form elements and their children just so you can get the value of a specific field.

  • #12
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Is there something special you have to do to use a variable?

    for example:

    Code:
    var ElementName = 'Phone';
    ContactForm.ElementName.value = 'some value';
    right now it's saying 'undefined' because it's trying to find an element literally name 'ElementName'.

    Regarding the question of IDs versus Names, I think it's a bit cleaner using only names, since you have to use names anyway, but I could be wrong. On this page though, I have multiple forms, some with similar field names... so to keep ids unique I would have to specify the form name too, making the id longer: id="ContactInfo_StoreName", instead of just name="StoreName". I suppose it could work either way.

  • #13
    Banned
    Join Date
    May 2005
    Location
    Midwest, U.S.
    Posts
    118
    Thanks
    1
    Thanked 26 Times in 23 Posts
    You dropped the document.

    var elementName = "Phone";

    alert(document.forms[0][elementName].value);

  • #14
    New Coder
    Join Date
    Sep 2008
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    So why doesn't this work:

    Code:
    var FieldReference = document.forms['StoreFrontContact'][ElementName];
    [FieldReference].parentNode.insertBefore(ErrorDiv, [FieldReference]);
    It's claiming that "[FieldReference].parentNode is undefined".


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •