0

I am iterating through html element which is input field by using jquery, but I get error. Here is my code:

$(".submit_button").on("click touch", function(e){
    e.preventDefault();

    var formdata = {};

    $(this).closest("div")
        .find("[data-field]")
        .each(function(i, val){
            var field = $(this).attr("data-field");             
            if($(this).is("[data-group]")) {
                var group = $(this).attr("data-role");
                formdata[group][field] = $(this).val() || "";
            } else {
                formdata[field] = $(this).val() || "";
            }
        });
    alert(JSON.stringify(formdata));
    return;
});

When I click submit button, the error console in firebug said that:

formdata[group] is undefined

How should it be written, so it is run correctly?

1
  • @Saty no I think it's OK as an object ({}). It's not really being used as a JavaScript array. Commented Sep 26, 2015 at 12:56

1 Answer 1

1

You have to define formdata[group]. Test this:

$(".submit_button").on("click touch", function(e){
e.preventDefault();

var formdata = {};

$(this).closest("div")
    .find("[data-field]")
    .each(function(i, val){
        var field = $(this).attr("data-field");             
        if($(this).is("[data-group]")) {
            var group = $(this).attr("data-role");
            if(!(group in formdata)){ //if group is not present in formdata, define it
               formdata[group] = {}; 
            }
            formdata[group][field] = $(this).val() || "";
        } else {
            formdata[field] = $(this).val() || "";
        }
    });
    alert(JSON.stringify(formdata));
    return;
});
Sign up to request clarification or add additional context in comments.

Comments

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.