2

I have a set of input fields on my page. They're setup as an array like so:

<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" /><br />
<input type="text" name="test[name][]" />

What i need to do next it to set a unique value in each textfield. But i don't know how to iterate over these fields with jQuery. My attempt failed: DEMO

$(function() {
    $.each('input[name="test[name][]"]', function() {
        $(this).val('blaat');
    });
});

Any idea how i can iterate over each input field, selecting them by name!? I don't have any influence on these controls. So i cannot give them an extra class name or anything like that. All i have are their names.

1
  • The brackets [] are invalid characters in names of HTML elements. Valid characters are a-zA-Z0-9_:. Commented Nov 20, 2012 at 8:18

2 Answers 2

3

The selector you use to get array just a is string but not array

'input[name^="test"]' should be $('input[name="test[name][]"]')

You can do it this way,

Live Demo

$(function() {
    $.each($('input[name^="test[name][]"]'), function() {        
        $(this).val('blaat');
    });
});

Sign up to request clarification or add additional context in comments.

2 Comments

$('input[name="test[name][]"]') should work fine too, i.e. without ^=
how can I add an array of elements to multiple form fields that have the same class/name attributes? If I implement this method, only the first value is appended to all input fields.
0

You could do something like

$(function() {
    $.each($('input[name^="test"]'), function() {
        $(this).val('blaat');
    });
});​

EDIT: More efficient

$(function() {
    $('input[name^="test"]').each(function() {
        $(this).val('blaat');
    });
});​

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.