13

I'm a jQuery newbie.

I have a simple form with n lines (although I'm not using html form):

<div id="myCities">
  <div class="line">City1: <input type="text" /></div>
  <div class="line">City2: <input type="text" /></div>
  <div class="line">City3: <input type="text" /></div>
  <button>Add Your Cities</button>
</div>

I have a javascript var called "users" with general users data:

var users = [
  { "username": "John", "year": 1999},
  more users...
]

When clicking on the button, I want to add an array of cities to the user's data (let's say we are working with John so he's [0])

I want the object to look like:

{ "username": "John",
  "year": 1999,
  "cities": [
    { "City1": $('.line input).val() },
    ... and so on for the 3 cities entered
  ]   
}

I tried using

$.each($('.line'), function() { 
   // but I'm not really sure what to put here 
});

Thanks!

James Montagne
  • 77,516
  • 14
  • 110
  • 130
idophir
  • 14,451
  • 5
  • 24
  • 21
  • 1
    When do you want to add the list of cities to the object? Will John click a "save" or "submit" button, or do you need to update it as he types, or something else? – hughes Jul 25 '11 at 14:08
  • When clicking the "Add your cities" button. Nothing fancy. – idophir Jul 25 '11 at 15:11

2 Answers2

32

Try this

var cities = [];

var $this, input, text, obj;
$('.line').each(function() { 
   $this = $(this);
   $input = $this.find("input");
   text = $this.text();
   obj = {};
   obj[text] = $input.val();
   cities.push(obj);
});

users[0].cities = cities;
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • Shouldn't you be using `var` on your local variables? – jfriend00 Jul 25 '11 at 14:45
  • 1
    If I define it inside each loop they will be defined for each iteration which is not required. For that reason I defined them outside the loop. – ShankarSangoli Jul 25 '11 at 14:47
  • Although @marc's solution is much more elegant, I ended up using this solution. I believe it is more general and will be helpful for more people. – idophir Jul 25 '11 at 16:11
  • btw, seems to me this is passing only a reference to object `obj` to the array, which means data in the objects get overwritten... I think... – edison23 May 07 '17 at 22:45
  • it should be `var cities = new Array();` rather than `var cities = [];` because the latter won't let you push to it. The error will show saying `.push` is not a valid method. – LatentDenis May 30 '17 at 14:12
  • you save my time :) – Hamid Talebi Aug 14 '18 at 05:00
5
$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});
marc
  • 6,103
  • 1
  • 28
  • 33