Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace getElementsByName with getElementsById not working

I have this code that works:

<script type="text/javascript" language="javascript">
function doStuff1(){
    var eml=document.getElementsByName('email')[0].value;
        msg=document.getElementsByName('message')[0];
    msg.value = eml + ' ' + msg.value;
    alert ('Message has been submitted');
    return true;  //return false to test just messagebox and updated message textarea
}
</script> 

However, when I use getElementById instead of getElementsByName then it stops working. That is the method would not show the alert dialog.

Of course I added a id attribute on the same tag with the name, like id="email" name="email"

This method is called when the submit button in the form is clicked.

What could be the problem?

like image 968
quarks Avatar asked Oct 04 '22 08:10

quarks


1 Answers

getElementById does not return a collection of elements, but only a single element. document.getElementById('email')[0].value is a semantic error.

Remove the [0]s.

like image 102
Explosion Pills Avatar answered Oct 11 '22 03:10

Explosion Pills