Andy Harvey Andy Harvey - 5 months ago 23
jQuery Question

How to access serializeArray key/values when key includes square brackets e.g. key[name]

I am serializing values submitted to a form

$(".my-form").submit (event) ->
values = {}
$.each $(this).serializeArray(), (i, field) ->
values[field.name] = field.value
return
console.log(values)


I now want to access these values, which usually is easy enough.

console.log(values.field)


However, in this case the form has input names that include square brackets

<input name="my_form[content]">


What is the correct way to access these values?

console.log(values)
returns
Object {utf8: "✓", my_form[content]: "my value"}


But I can't find the correct syntax to get only the
my_form[content]
value.

console.log(values.my_form[content])
returns
Uncaught ReferenceError: content is not defined

Answer

As the following line

values.my_form[content]

tries to find a property my_form with a key content. Where content is considered as variable and found to be undefined.


Use obj['key'] with '' quotes..

values['my_form[content]']
Comments