Search code examples
javascriptjquerynested-loops

Jquery getting nested inputs of Div, placing in Object


I am at my wits end with this nested loop. I am trying to create an object with nested objects in it grouped by the containing div id. So far this is what I have:

$('#survey-submit').on('click', function (e) {


    var formData = {};
    var item = {};
        $("div[id^='question-']").each(function () {
            var id = '#' + $(this).attr('id');
            var $this = $(this);
            formData[id] = $this.children('input, select,checkbox').each(function () {
                item[this.name] = this.value;
            });


            //console.debug(formData);
        });
        console.debug(formData);
    return false;
});

The result of the console log is all the input elements of the divs that have the start like question, I get the expected number of new objects all dynamically named, but they all contain the same thing.

The contents of each object are not specific to the this object I am trying to generate it from, any help would be appreciated!


Solution

  • I found a solution to the problem here : jquery how to get form element types, names and values

    I wound up doing this:

        $("div[id^='question-']").each(function () {
                var id = '#' + $(this).attr('id');
                var $this = $(this);
          var inputs= $(id+' :input').map(function(index, elm) {
        return {name: elm.name, value: $(elm).val()};
    }).get();
           formData[id]=inputs;
            });