Sukalyan Ghoshal
Sukalyan Ghoshal

Reputation: 33

jQuery - creating an array of objects containing key - value pairs

I have the following HTML code :

<div class="input_data">
    <input type="text" name = 'firstname' class="fname">
    <input type="text" name = 'lastname' class="lname">
</div>
<br>
<br>
<div class="input_data">
    <input type="text" name = 'firstname'class="fname">
    <input type="text" name = 'lastname' class="lname">
</div>
<button id="sbmt">Submit</button>

I am trying to assign the pairs of strings from the inputs as object in a jQuery array through the following code :

$('#sbmt').on('click', function() {

    var this_row = {};
    //var all_rows = [];

    $('.input_data').each(function(){

        $('> input', this).each(function(){

            //this_row[$(this).attr('name')] = $(this).val();
            //this_row.push($(this).attr('name')) = $(this).val();
            keyvalue = $(this).attr('name');
            namevalue = $(this).val();
            alert(keyvalue + " is : " + namevalue);
            this_row[keyvalue] = namevalue;
            //all_rows.push({$(this).attr('name'):$(this).val()});
        });

    });

As you can see I have kept the statements with all_rows commented - actually it is giving error that use of "this" is not legal here.

That being done, the code in its current form is only storing the values from the second set of inputs.

I actually need to generate an array of objects like

[{firstname:firstname-1, lastname:lastname-1}, {firstname:firstname-2, lastname:lastname:2}]

How can I make that happen? Also I would like to know how to make the statement all_rows.push({$(this).attr('name'):$(this).val()}); work.

Upvotes: 0

Views: 3780

Answers (1)

Vasyl Moskalov
Vasyl Moskalov

Reputation: 4630

You need something like this one:

$('#sbmt').on('click', function() {

    var all_rows = [];

    $('.input_data').each(function() {
        var this_row={};
        $(this).find("input").each(function () {
            keyvalue = $(this).attr('name');
            namevalue = $(this).val();
            this_row[keyvalue] = namevalue;
        });
        all_rows.push(this_row);

    });
    console.log(all_rows);
   });

https://jsfiddle.net/9kxxwz0n/

Upvotes: 2

Related Questions