TheGeekZn
TheGeekZn

Reputation: 3914

Create JSON from Dom elements in a `div`

I need to get all the elements inside a div, which could be multiple inputs, checkboxs, radiobuttons etc, and convert the id or name and value of it to a JSON readable format.

I've tried to use a modified version of the the following SO question, which resulted in the following:

var data = $('#item').map(function() {
    return {
        content: $(this).val()
    };
}).get();

console.log(data);

<div id="item">
    <input class="item" id="test" value="data" />
</div>

But it doesn't return any value.

Upvotes: 0

Views: 561

Answers (2)

Dibu
Dibu

Reputation: 891

this may help you

var map = {};

    $("#item").children().each(function (i, element)
       {
          map[$(element).attr("id")] = $(element).val();
        }
     );

Upvotes: 0

Quentin
Quentin

Reputation: 943134

You are running your map access the div (which doesn't have a value as it is not a form control), not the input inside it.

You probably want '#item :input' are your selector.

Upvotes: 3

Related Questions