...">

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 getElementByIdinstead getElementsByName, it stops working. That is, the method does not display a warning dialog box.

Of course, I added the attribute idto the same tag with namefor exampleid="email" name="email"

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

What could be the problem?

+5
source share
1 answer

getElementByIddoes not return a set of elements, but only one element. document.getElementById('email')[0].valueis a semantic mistake.

Remove [0]s.

+4
source

All Articles