João Serra
João Serra

Reputation: 253

Get values from HTML Form arrays in Javascript

In my forms i have some arrays being sent back like this

<input class="checkbox-service" name="services['electricity']" type="checkbox"> 

<input class="checkbox-service" name="services['water']" type="checkbox"> 

<input class="checkbox-service" name="services['gas']" type="checkbox">

Now i need to be able to access all of these values in my jquery so i can somehow inject them into an input hidden, how can i do this in a way that doesn't make me have to duplicate code?

Upvotes: 0

Views: 111

Answers (1)

nibnut
nibnut

Reputation: 3127

Easiest way would be to give each input a unique id attribute - then you can grab them by id. But if you want to use the name attribute, you'll need to escape those special characters when used in selectors:

var first_checkbox = $("input[name='services\[\\'electricity\\'\]']");

Note that you need to escape the single quotes twice... You might not need them either: for instance with PHP, they are not required and you could use "services[electricity]" directly.

Hope this helps!

Upvotes: 2

Related Questions