2

The html inside contact_info div is appended dynamically using jquery append function (multiple contact person can exist). How can I produce following json format from the input using jquery?

{
   "Company":[
      {
         "company_name":"ABC Company",
         "contact_info":[
            {
               "contact_person":"Mr. ABC",
               "email":"[email protected]"
            },
            {
               "contact_person":"Mr. XYZ",
               "email":"[email protected]"
            }
         ]
      }
   ]
}

<div class="form-group">
    <label>Company Name
    </label>
    <div class="col-md-5">
        <input name="company_name" id="company_name" type="text" class="form-control">
    </div>
</div>

<div id="contact_info">
    <div class="row">
        <div class="form-group">
           <div class="row">
                <label>Contact Person
                </label>
                <input name="contact_person" id="contact_person" type="text" class="form-control" maxlength="100">
                <label>Email
                </label>
                <input type="email" name="cp_email" id="cp_email" class="form-control" maxlength="100">
            </div>
        </div>
    </div>
</div>

1 Answer 1

1
<button onclick="addCompany()">Add Company</button>

-----------Script------------

var company=[];
function addCompany()
{
  var pushed=0;
$.each(company, function(i, data) {

    if(data.company_name===$('#company_name').val())
    {

      company[i].contact_info.push({
               "contact_person":$('#contact_person').val(),
               "email":$('#cp_email').val()
            });
       pushed++;

      return false;

    }


});
if(pushed==0)
    {

      var obj={
    "company_name":$('#company_name').val(),
         "contact_info":[
            {
               "contact_person":$('#contact_person').val(),
               "email":$('#cp_email').val()
            }
            ]
};
company.push(obj);
    }

alert(JSON.stringify(company));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. It works fine for single contact person. But there can be multiple contact person. The inner html of <div class="contact_info"> is appended dynamically with it if I add another contact person. And I am actually facing problem to fetch input data and make a json output (as I mentioned above) for multiple contact person. And I have to handle it in javascript.
Hi,I edited my answer by applying condition for same company name,if u add two time with same comapny name the new contact will be added to the same object .

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.