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!
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.
The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.
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;
$.each($('.line'), function() {
var key = $(this).text().replace(/.*(City\d+).*/,'$1');
user.cities[key] = $(this).find('input').val();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With