12

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!

2
  • 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? Commented Jul 25, 2011 at 14:08
  • When clicking the "Add your cities" button. Nothing fancy. Commented Jul 25, 2011 at 15:11

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

6 Comments

Shouldn't you be using var on your local variables?
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.
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.
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...
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.
|
5
$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});

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.