0

I'm assigning values to array in forloop But it gives an error that array variable is undefine. following is my code.

$(document).ready(function(){

   $("#SubmitBtn").live('click',function(){

        var cnt = $("#TotalCnt").val();
        var data = [];

        for(var i=1; i<=cnt; i++)
        {
           var fname = $('#fname_'+i).val();
           var lname = $('#lname_'+i).val();
           var address = $('#address_'+i).val();

           data[i]["fname"] = fname;
           data[i]["lname"] = lname;
           data[i]["address"] = address;
        }

   });

}); 

when I'm assigning value to array it gives error "data[i] is undefined"

1
  • Just out of curiosity, which jQuery version are you using? Commented Jan 20, 2015 at 7:03

1 Answer 1

3

Try to create an empty object first, because initially data[i] is undefined. And undefined does not contains any property under it.

$(document).ready(function(){

   $("#SubmitBtn").live('click',function(){

        var cnt = $("#TotalCnt").val();
        var data = [];

        for(var i=1; i<=cnt; i++)
        {
           var fname = $('#fname_'+i).val();
           var lname = $('#lname_'+i).val();
           var address = $('#address_'+i).val();
           data[i] = {};
           data[i]["fname"] = fname;
           data[i]["lname"] = lname;
           data[i]["address"] = address;
        }

   });

});
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.