0

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.

1 Answer 1

2

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/

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

3 Comments

Thanks for your suggestions vasyl. but the problem is persisting - the array is showing only the last roes of inputs...
I just run this code from jsfiddle and take a small screenshot. In all_rows persists all four input value splitted by two row. Screenshot: zimagez.com/miniature/screenshot-20032016-071511.php
Vasyl - I'm sorry - I made some mistake about your suggestion. It is working just the way I want. Many thanks..!!

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.