Alex Schwifty
Alex Schwifty

Reputation: 59

How to use nested HTML <input[name=""]> as JavaScript Object/Array keys

I am trying to prepare the following inputs

<input type="text" name="customer[firstname]">
<input type="text" name="customer[surename]">
<input type="text" name="customer[cuid]">

to use them in an ajax function to validate them with PHP. The array I will receive shall look like $data['customer']['firstname'].

This was my first attempt

$.each($('input[name^="customer"]').serializeArray(), function() {
    data[this.name] = this.value;
});

Problem: the array in the request looks like $data["[customer[firstname]"] and it is not pretty and I will have different keys like product[...], order[...]. Then I will need the "customer" as seperate key.

Then I thought about to remove and to replace the brackets and just to create my own array before sending. But there are more problems than I thought...

var data = {};

$.each($('input[name^="customer"]').serializeArray(), function() {
    let name = this.name.replace( ']', '' ).replace( '[', ',' ).split(',')[1];
    data['customer'].push({[name] : this.value}); // <- Error: push is not a function
    data = { 'customer' : {[name] : this.value} }; // <- Problem: data gets overwritten with the next key:value
    data['customer'][name] = this.value; // <- Error: `customer` not defined
});

This 3 examples are just a few I tried...

Does someone know how to solve this problem?

Upvotes: 0

Views: 305

Answers (1)

rajesh
rajesh

Reputation: 219

Now it will works fine. Please check it.

var data = { customer: [] }; 
$.each($('input[name^="customer"]').serializeArray(), function() {
     var new_name = this.name.replace("customer[", "");
         new_name = new_name.replace("]", "");
         data['customer'].push(new_name);
         data['customer'][new_name] = this.value;
  });

Upvotes: 1

Related Questions