3

Just trying to alert the value entered in the phone field, but it alerts undefined:

<script type="text/javascript">

function foo() {
   alert(document.getElementsByName("phone").value);
   return false;
}

</script>

<form action="foo.php" method="post" onsubmit="return foo()">
    <label>Name:</label>
    <input type="text" name="name" />
    <label>Phone:</label>
    <input type="text" name="phone" />
    <label>Email:</label>
    <input type="text" name="email" />
    <label>Message:</label>
    <textarea name="message"></textarea>
    <input type="submit" value="Submit" name="submit" />
</form>

How to get it to work? Also, I read that getElementsByName is supported in all major browsers, is that true?

Brandon
  • 247
  • 2
  • 3
  • 5

4 Answers4

5

document.getElementsByName(...) returns a collection of DOM elements.

Have you tried this?

document.getElementsByName("phone")[0].value

Based on the snippet of code, instead of using just names, you may want to use IDs instead. In that case, you can call...

... HTML ...
<input type="text" id="phone" />

... Javascript ...
document.getElementById("phone").value

... to retrieve the element you wanted.

DashK
  • 2,640
  • 1
  • 22
  • 28
  • ahh very good, didn't know it was returning an array. I know about get element by id but would rather keep not clog up the markup if it's not necessary (my forms always have names anyway for server side processing), unless get element by id is significantly better performance wise, is it? – Brandon Apr 30 '11 at 18:53
  • It's actually not an array, rather a live NodeList (or HTMLCollection in some browsers) of elements. – duri Apr 30 '11 at 18:55
  • @Brandon - Check this site out: http://goo.gl/SX5SB. On my machine (Mac + Chrome), getElementById is actually slower than getElementsByName by 3ms. FYI. @duri - You're right. It returns a Collection, not an Array. Thanks for pointing that out. – DashK Apr 30 '11 at 19:11
0

You're getting collection of elements, not one element.

   alert(document.getElementsByName("phone")[0].value);
duri
  • 14,991
  • 3
  • 44
  • 49
0

An element needs to have an id for this to work well. For example

  <input type="text" id="phone">Phone:</input>

with

  document.getElementByID("phone");
Hogan
  • 69,564
  • 10
  • 76
  • 117
0

Not that the method is get*Elements*ByName. It returns multiple elements in an array.

What you need is document.getElementsByName("phone")[0].value

And rather then by name, I would suggest using ID's.

Then you could do document.getElementByID("phone").value

McKayla
  • 6,879
  • 5
  • 36
  • 48