Reputation: 410
What's the best way to loop through an elements if the name attribute is an array?
for example
<input type="hidden" name="data[test-1]" value="1" />
<input type="hidden" name="data[test-2]" value="2" />
<input type="hidden" name="data[test-3]" value="3" />
<input type="hidden" name="data[test-4]" value="4" />
and then i will be able to get the array index
test-1 test-2 test-3 test-4
Help much appreciated!
thanks,
Upvotes: 2
Views: 11282
Reputation: 8426
You can use a css selector like so
$('input[name^="data"]').each(function(){
//code
alert($(this).attr('name'));
});
Here's a JS Fiddle example http://jsfiddle.net/cqatyghb/
This is probably the best selector. Basically test that the selector starts with data[test-
and ends with ]
$('input[name^="data\\[test-"][name$="]"]').each(function(){
alert($(this).attr('name'));
});
Upvotes: 6
Reputation: 410
here' the actual implementation combining Carl and Amit's solutions
$("input[name^='data']").each(function(){
name = $(this).attr("data").replace(/^\w+|[[]]/g,"");
name = name.replace(/[\[\]']+/g,'');
});
Upvotes: 0
Reputation: 8761
This way You would use $.each
:
$('input[type=hidden]').each(function(index, el) {
console.log(index, el.value);
});
Upvotes: 0
Reputation: 59252
You have to escape special characters with double backslash \\
For now, you can do this
$('[name^="\\[data-"]').each(function(){
console.log($(this).attr("name").replace(/^\w+|[[]]/g,""));
});
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
Upvotes: 2