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
78.9k14 gold badges115 silver badges132 bronze badges
asked Jul 25, 2011 at 14:05
idophir
14.9k5 gold badges26 silver badges21 bronze badges
-
1When 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– hughes2011年07月25日 14:08:15 +00:00Commented Jul 25, 2011 at 14:08
-
When clicking the "Add your cities" button. Nothing fancy.idophir– idophir2011年07月25日 15:11:34 +00:00Commented Jul 25, 2011 at 15:11
2 Answers 2
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;
answered Jul 25, 2011 at 14:14
ShankarSangoli
69.9k13 gold badges96 silver badges124 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
jfriend00
Shouldn't you be using
var on your local variables?ShankarSangoli
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.
idophir
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.
edison23
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...LatentDenis
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. |
$.each($('.line'), function() {
var key = $(this).text().replace(/.*(City\d+).*/,'1ドル');
user.cities[key] = $(this).find('input').val();
});
answered Jul 25, 2011 at 14:15
marc
6,2431 gold badge31 silver badges33 bronze badges
Comments
lang-js