How do I submit a form in javascript using the getElementsByName method?

frequent picture frequent · Sep 24, 2012 · Viewed 7.2k times · Source

I'm just curious about a certain scenario:

If I want to submit a form using getElementById using the following code below:

 document.getElementById("form_id").submit();

it works fine. However, trying similar code using getElementsByName in the code below:

document.getElementsByName("form_name").submit();

doesn't work, although there is only a single element with this name: form_name.

So my question is?

Is it possible to submit a form using getElementsByName, or do I need to give an id to all of my forms.

Thanks!

Answer

chrisf picture chrisf · Sep 24, 2012

document.getElementsByName returns an array, so you need to access it with the array index notation:

document.getElementsByName("form_name")[0].submit();