get elements by array name JS, JQuery

时间:2016-08-31 18:33:00

标签: javascript php jquery

I have this HTML

<input type="text" name="object[A][Name]">
<input type="text" name="object[A][Description]">
<input type="text" name="object[B][Name]">
<input type="text" name="object[B][Description]">

but when i try to get with:

var x = document.getElementsByName("object");
var x = document.getElementsByName("object[]");
var x = document.getElementsByName("object[][]");
var x = $("[name='object']");
var x = $("[name='object[]']");
var x = $("[name='object[][]']");

x is empty

I need get A, Name/Description and value

Normally I process this names in PHP like this:

foreach($_POST['object'] as $objectgroup=>$value)
{
  /* work here */
}

2 个答案:

答案 0 :(得分:0)

Use ^= to match the starting string:

var x = $("[name^='object']"); // Get all elements
var x = $("[name^='object[A']"); // Get only "object[A]" elements
var x = $("[name='object[A][Description]']"); // Matches full element name

Demo

答案 1 :(得分:0)

You want to select inputs whose name attribute starts with "object", so use the ^= operator (docs):

var x = $('input[name^=object]');