2

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,

4 Answers 4

6

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'));
});
Sign up to request clarification or add additional context in comments.

1 Comment

this actually works but i have to combine @amit joki regex to make it work better.. thanks guys, you rock!
2

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,""));
});

jQuery Docs:

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").

Comments

0

This way You would use $.each :

$('input[type=hidden]').each(function(index, el) {
   console.log(index, el.value);
});

Comments

0

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,'');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.