GetElementsByName with array like name

23,004

Solution 1

<input name="color[3]" id="color_3" type="text" />

var element = document.getElementsByName("color[3]");

alert(element[0].id);

It works fine .. The thing you should have in your mind is Return type is an array of elements not a single element

Solution 2

If you want all of the color inputs, you can use querySelectorAll instead to query for the name attribute:

document.querySelectorAll("input[name^='color[']")

This looks through the document for all input tags whose name attribute starts with color[. Here is a fiddle for this.

If you only want color[3], you can use:

var color3 = document.getElementsByName("color[3]");
console.log(color3[0]);
Share:
23,004
AndreaBogazzi
Author by

AndreaBogazzi

Javascript and php software developer based in Italy. Fan and contributor of fabricjs. Working at Shutterstock.

Updated on August 06, 2020

Comments

  • AndreaBogazzi
    AndreaBogazzi almost 4 years

    i often use this notation when i name my controls in order to get an array in POST or GET.

    <input name="color[1]" type="text" />
    <input name="color[2]" type="text" />
    <input name="color[3]" type="text" />
    

    so in my scripts i can do

    <?php $data=$_GET["color"]; 
    for each ($color as $key=>$value) {
       doSomething();
    } ?>
    

    Often happens that i need to get those id back in javascript , but i cannot get them , so i often add an ID to each element in html like that

    <input name="color[3]" id="color_3" type="text" />
    

    so that i can use document.getElementsById('color_3')

    Instead i would like to find way to use document.getElementsByName(color[3])... but i cannot really get it to work.

    Any help?