2

I'm trying to insert <span class=""> value inside an array arrChairs[], and insert this array inside an object room{}, obviously I'm doing it in the wrong way, because it isn't working, here are the codes:

html:

<div id="table">
    <a href="" id="foo1">
        <span class="chair1"></span>
        <span class="chair2"></span>
        <span class="chair3"></span>
        <span class="chair4"></span>
    </a>
    <a href="" id="foo2">
        <span class="chair1"></span>
        <span class="chair2"></span>
    </a>
    <a href="" id="foo3">
        <span class="chair1"></span>
        <span class="chair2"></span>
        <span class="chair3"></span>
    </a>
</div>

js:

room = {},
arrChairs  = [];

$('#table a').each(function(i){
    tableId = $('#table a:eq('+i+')').attr('id');
    room[tableId] = {};

    $('#table a:eq('+i+') span').each(function(i){
       arrChairs.push( $(this).attr('class') ); 
    });
    room[tableId].chairs = arrChairs;
});

I don't know why it isn't working.

This is what arrChair is return me on console.log:

['chair1','chair2', 'chair3', 'chair4', 'chair1', 'chair2', 'chair1', 'chair2', 'chair3']

It's concatenating all the content. Some help would be appreciated

1 Answer 1

2

You are putting <span class=""> all together since you don't initialize arrChairs for each <a> in the root <div>. Try with this instead:

room = {};

$('#table a').each(function(i){
    tableId = $('#table a:eq('+i+')').attr('id');
    room[tableId] = {};
    var arrChairs  = [];

    $('#table a:eq('+i+') span').each(function(i){
       arrChairs.push( $(this).attr('class') ); 
    });
    room[tableId].chairs = arrChairs;
});

An make the console.log for the room instead of arrChairs.

Hope this helps

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.