Reputation: 3
I'm hoping someone can help me construct the below array from HTML using jQuery. I've tried with the below jQuery but it isn't outputting the array correctly:
I've put everything in jsfiddle
Thanks in advance for any help
var options = [];
var a = 0;
$(".option").each(function(i) {
options[a] = [];
options[a]["label"] = $('.label', this).text();
options[a]["value"] = $('input', this).val();
a++;
});
This is an example of my HTML:
<div class="option">
<div class="label">Title</div>
<input type="text" value="TitleValue">
<div class="label">SKU</div>
<input type="text" value="SKUValue">
<div class="label">Currency</div>
<input type="text" value="CurrencyValue">
</div>
<div class="option">
<div class="label">Title</div>
<input type="text" value="TitleValue">
<div class="label">SKU</div>
<input type="text" value="SKUValue">
<div class="label">Currency</div>
<input type="text" value="CurrencyValue">
</div>
<div class="option">
<div class="label">Title</div>
<input type="text" value="TitleValue">
<div class="label">SKU</div>
<input type="text" value="SKUValue">
<div class="label">Currency</div>
<input type="text" value="CurrencyValue">
</div>
The structure of the array should look like this:
array = [
"0" => [
'Title' => 'TitleValue',
'SKU' => 'SKUValue',
'Currency' => 'CurrencyValue'
],
"1" => [
'Title' => 'TitleValue',
'SKU' => 'SKUValue',
'Currency' => 'CurrencyValue'
]
]
Upvotes: 0
Views: 317
Reputation: 12717
This assumes your html structure is always div with class of label followed by input.
With some changes to your html, you could make this less fragile. Perhaps tieing the label and input together with a data attribute.
var options = [];
var a = 0;
$(".option").each(function (i) {
options[a] = {};
$(this).find('.label').each(function() {
var title = $(this).text();
var value = $(this).next('input').val();
options[a][title] = value;
});
a++;
});
console.log(options);
http://jsfiddle.net/hrnzsegf/2/
Upvotes: 1