2

i have been trying to create objects inside a loop. Below is my code.

<div class="container">
<div class="personDetails">
<input type="text" class="abc" id="Name1">
<input type="text" class="abc" id="Age1">
</div>
<br /><br />
<div class="personDetails">
<input type="text" class="abc" id="Name2">
<input type="text" class="abc" id="Age2">
</div>
<button onclick="getDetails()">Check Value</button>
</div>

And below is the javascript..

function getDetails(){
var myObj = {};
$('.personDetails').each(function(){
        $(this).children().each(function(){
myObj[$(this).attr('id')] = $(this).val();
            });
    });
console.log(myObj);
}

And below is what it looks like in console. but i dont want it all into one object. what i want is each person should have each object created in that .each loop. i know i m close but cant figure out what i am doing wrong.

Object {Name1: "cfr", Age1: "15", Name2: "fgatat", Age2: "25"}

I want to do like

person1 {Name: "cfr", Age: "15"}, 
person2 {Name: "fgatat", Age: "25"}
4
  • Create an Array outside the loop, create each new object inside the loop, and add each new object to the array. Commented May 15, 2017 at 14:31
  • I was doing that but i am messing it all up.. Please advise if you can just copy paste the function it should be like. Sorry for trouble and Thanks Commented May 15, 2017 at 14:33
  • What is the purpose of this? Generally you use inputs to gather data from the user, and use that data for something, for instance sending it to a server, and then you would'nt do it this way at all, you'd just serialize the inputs instead Commented May 15, 2017 at 14:38
  • i dont want to use form, all the div named personDetails will be added dynamically through jquery depending on how many div's they want, then when the button is clicked, i want to loop through every field and filter its value and they will of course send to server using $.ajax. server side script knows how many objects he is expecting and will loop through all of them and store in database. one posted object will have one or more objects. Commented May 15, 2017 at 14:44

5 Answers 5

4

Here is one of possible solutions:

function getDetails(){
  var myObj = [];
  $('.personDetails').each(function() {
        var person = {};
        $(this).children().each(function(){
            person[$(this).attr('id')] = $(this).val();
        });
        myObj.push(person)
    });
   console.log(myObj);
}
Sign up to request clarification or add additional context in comments.

3 Comments

But will you not still have different keys within the objects for each person, like name1, name2 etc.?
Yes. But now numbering may be removed from those IDs during creation. Or any other trick may be done.
actually i wont be using id, will get data using name attr. and every object will have name and age
0

You should declare a var with window[myvar]

function getDetails(){
$('.personDetails').each(function(i){
  i+=1;
  window["person"+i] = {};
  $(this).children().each(function(){
    window["person"+i][$(this).attr('id')] = $(this).val();
  });
});
console.log(person1);
console.log(person2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="personDetails">
<input type="text" class="abc" id="Name1">
<input type="text" class="abc" id="Age1">
</div>
<br /><br />
<div class="personDetails">
<input type="text" class="abc" id="Name2">
<input type="text" class="abc" id="Age2">
</div>
<button onclick="getDetails()">Check Value</button>
</div>

Comments

0

Here's another way to do this, that gives you exactly the output you're asking for

$('#btn').on('click', function() {
  var result = $('.personDetails').toArray().reduce(function(a, b, i) {
    return a['person' + (++i)] = {
      Name: $(b).find('[id^=Name]').val(),
      Age: $(b).find('[id^=Age]').val()
    }, a;
  }, {});

  console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="personDetails">
    <input type="text" class="abc" id="Name1">
    <input type="text" class="abc" id="Age1">
  </div>
  <br /><br />
  <div class="personDetails">
    <input type="text" class="abc" id="Name2">
    <input type="text" class="abc" id="Age2">
  </div>
  <button id="btn">Check Value</button>
</div>

Comments

0

If the ids are always in the same form NameX and AgeX, you can update your code to extract only the Name and Age parts using $(this).attr('id').replace(/\d+$/, '') and use them as properties.

This is how should be your code:

function getDetails() {
  var results = [];
  $('.personDetails').each(function() {
    var person = {};
    $(this).find('input[type="text"]').each(function() {
      person[$(this).attr('id').replace(/\d+$/, '')] = $(this).val();
    });
    results.push(person)
  });
  console.log(results);
}

Demo:

This is a working Demo snippet:

function getDetails() {
  var results = [];
  $('.personDetails').each(function() {
    var person = {};
    $(this).find('input[type="text"]').each(function() {
      person[$(this).attr('id').replace(/\d+$/, '')] = $(this).val();
    });
    results.push(person)
  });
  console.log(results);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="personDetails">
    <input type="text" class="abc" id="Name1">
    <input type="text" class="abc" id="Age1">
  </div>
  <br /><br />
  <div class="personDetails">
    <input type="text" class="abc" id="Name2">
    <input type="text" class="abc" id="Age2">
  </div>
  <button onclick="getDetails()">Check Value</button>
</div>

Comments

0

Why not try the following, add a name to your input that uses the following format inputName[index]. So that you can extract the code using indexes. The selector to extract the value from the input would be something along the lines of 'input[name="inputName[' + index + ']"'. Then all you need to to is use this in for loop. You might even have a function that generates all your fields based on a jQuery function.

(function($) {
  //Object
  function Person(name, age) {
    var self = this;
    self.name = name;
    self.age = age;
    return self;
  }

//actual getDetails function
  function getDetails() {
    var myObj = [];
    var name, age; //These vars are added for readabilitys sake. You could place them directly in the new Person()
    for (i = 0; i < 3; i++) {
      
      name = $('input[name="Name[' + i + ']"').val();
      age = $('input[name="Age[' + i + ']"').val();
      myObj.push(new Person(name, age));
    }

    console.log(myObj);
  }

 //Click Binding
  $("#getDetails").on('click', getDetails);

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="personDetails">
    <input type="text" class="abc" name="Name[0]">
    <input type="text" class="abc" name="Age[0]">
  </div>
  <br /><br />
  <div class="personDetails">
    <input type="text" class="abc" name="Name[1]">
    <input type="text" class="abc" name="Age[1]">
  </div>
  <div class="personDetails">
    <input type="text" class="abc" name="Name[2]">
    <input type="text" class="abc" name="Age[2]">
  </div>
  <button type="button" id="getDetails">Check Value</button>
</div>

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.