2

I'm very much a newb when it comes to JQuery, and this arose out of an attempt to learn how to use it.

I have a form defined in which I have a series of inputs like the following:

<input name="Name[]">

I have successfully set up JQuery to clone a variable number of these and the submit works perfectly. When I submit this to PHP, I get the post data I am expecting.

["Name"]=> array(6) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=>  string(0) "" [4]=> string(0) "" [5]=> string(0) "" }

The problem I'm running into, though, is attempting to populate these form elements with the json data returned by my PHP. When I try to set the values of these elements in the form using:

$('[name='+key+']', frm).val(value);

where (for instance) key = Name[0]

I haven't had much luck and get an error:

Uncaught Error: Syntax error, unrecognized expression: [name=Name[0]] 

Apparently it doesn't like the brackets in there? Is there a way to access elements in this manner?

3 Answers 3

1

Just take my answer as a suggestion only.
You can use the index/position of the input with eq function to set the value

example

$('[name="Name[]"]', frm).eq( key ).val( value );

or

$('[name="Name[]"]:eq('+key+')', frm).val( value );

Where key is the index/position of the input in the array ( ie: 0, 1, 2, .... )
Read more here http://api.jquery.com/eq/

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

1 Comment

Thank you for the response it's exactly what I needed!
1

You need to escape the [] with double backslash // for it to work.

$('input[name="Name\\[0\\]"]')

Try this

key= key.replace(/\[/g, "\\\\[");
key= key.replace(/\]/g, "\\\\]");

$('[name="'+key+'"]', frm).val(value);

1 Comment

I couldn't get this to work, but I appreciate you taking the time to respond :)
1

The name of the element stays Name[] in JavaScript and hence jQuery as well. Indexing the name is only required for PHP. jQuery would simply return a collection (just like if the name hadn't used []) with each jQuery object accessible using the .eq() method.

<input name="Name[]" />
<input name="Name[]" />

var jsonResp = ["hello", "world"];

$.each( jsonResp, function( idx, val ) {
    $( '[name = "Name[]"]' ).eq( idx ).val( val );
});

JSFiddle Demo

3 Comments

Thank you! This led me to exactly what I needed.
Apparently I can't accept two answers... despite both of them being spot-on... and I'm not sure who answered first...
@James, it's okay mate. I appreciate that you cared to comment. :)

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.