0

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'
            ]

        ]
1
  • 2
    Make options[a] and object like options[a] = {}; In JS arrays only have numeric keys and objects are what you are referring to as an assoc array or hash. Commented Jan 9, 2015 at 1:03

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

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.