Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript problem: getElementsByName() doesn't work for me [duplicate]

Tags:

javascript

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?

like image 983
Brandon Avatar asked Jan 27 '26 16:01

Brandon


1 Answers

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.

like image 124
DashK Avatar answered Jan 30 '26 06:01

DashK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!