4

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?

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63

2 Answers2

11

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]);
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
4
<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

Prasath K
  • 4,950
  • 7
  • 23
  • 35
  • I'm gonna try again. i tried and tried and tried with firefox console.... OK it works... i can swear this morning, in my room, was not working.. Any chance i can write xxx in some xml? i don't think i can write xml tag name with "[" inside. – AndreaBogazzi Aug 06 '13 at 08:20
  • @AndreaBogazzi You can write xml in that way .. See here : http://jsfiddle.net/xE6bh/ – Prasath K Aug 06 '13 at 08:42
  • i get "non well formed" if i write like that... 2 Prosciutto 0.00 6.00 NSSS – AndreaBogazzi Aug 06 '13 at 09:02
  • Yupp i tried .. Issue is because of ']' but don't know the reason – Prasath K Aug 06 '13 at 09:36
  • 1
    Is not allow in xml specs i see. i solved doing xxx and writing a bit of javascript that check if there is attribute index, and then modify the tagname name +'['+key +']' and it works. – AndreaBogazzi Aug 06 '13 at 09:43