Re: Best Way to access Input fields

Tech-Archive recommends: Fix windows errors by optimizing your registry



Dave Anderson said the following on 1/20/2006 3:58 PM:
Praveen wrote:
var InpObj= document.getElementByName("FrmInput")

There is no such method. "Element" is singular when sought by id, and plural when sought by name:


    container.getElementById(...)
    container.getElementsByName(...)

Recently I came to know that following is a better way to access
objects.

var InpObj= document.Frm.elements["FrmInput"] .

I don't know if I consider that better -- it is the old DOM Level 0 way of doing it, which means it will work with virtually any browser. But virtually any browser can do it with the new DOM methods as well.

Depending on how the HTML is defined.

<input name="myInput">

myInputValue = document.getElementById('myInput').value;

will only work in IE as any other browser won't use the ID in place of the NAME.

Any modern browser will pick it up this way:

<input id="myInput">
myInputValue = document.getElementById('myInput').value;

But, Form Elements with an ID but no NAME don't get submitted to the server. So, if you are going to submit the form and use the NAME attribute, then you are better off (simpler) to use the forms collection:

document.forms['formNameorID'].elements['elementNAMEnotID'].value;

I changed my previous way of posting that from formNAMEnotID due to a discussion with Lasse about ID's and NAME's on Form Elements.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
.



Relevant Pages

  • Re: [PHP] Prefilled forms (solved)
    ... No I am saying that if you have: ... >> I had some prefilled form elements where I set the ... It's up to each browser whether it keeps ... Protect your identity with Yahoo! ...
    (php.general)
  • Re: [PHP] Prefilled forms (solved)
    ... > I had some prefilled form elements where I set the ... The entire issue is up to the client's browser and has nothing to do ... The Magazine for PHP Professionals – www.phparch.com ...
    (php.general)
  • Re: [PHP] Going from simple to super CAPTCHA
    ... If, however, one browser decides tomorrow to use the "tab" order ... The HTML spec says that form elements should be presented in the order ... it's not his fault. ...
    (php.general)
  • Creating new form elements on a webpage
    ... Is it possible with JavaScript to create new form elements on a ... webpage that has already loaded in the browser? ...
    (comp.lang.javascript)
  • Re: Form elements resistant to styles
    ... Formatting the look of these two elements is problematic. ... I have no light blue around a select box. ... Why do you want to mess with my browser and operating system? ... Consider that the clueless are *used* to seeing these form elements as ...
    (comp.infosystems.www.authoring.stylesheets)