1

I have an array like this:

var arr = [
            { Group: 'Fruits', Name: 'Apple' },
            { Group: 'Fruits', Name: 'Pears' },
            { Group: 'Veggies', Name: 'Tomatoes' },
            { Group: 'Veggies', Name: 'Carrots' }
          ];

I want to create checkboxes for each group in my HTML container

so I get an output like this:

<div id="container">
    <h4>
        Fruits</h4>
    <ul id="Fruits">
        <li>
            <input type="checkbox" name="Apples" id="Fruits-Apples" /><label>Apples</label></li>
        <li>
            <input type="checkbox" name="Pears" id="Fruits-Pears" /><label></label>Pears</li>
    </ul>
    <h4>
        Veggies</h4>
    <ul id="Veggies">
        <li>
            <input type="checkbox" name="Tomatoes" id="Veggies-Tomatoes" /><label>Tomatoes</label></li>
        <li>
            <input type="checkbox" name="Carrots" id="Veggies-Carrots" /><label>Carrots</label></li>
    </ul>
</div>

What is the best way to do this using jquery?

0

3 Answers 3

1

I fixed Kanishka's code so it works:

var content = '';
var prev = '';

for (var arrayIndex in arr)
{
    if (prev != arr[arrayIndex].Group)
    {
        prev = arr[arrayIndex].Group;
        content = '<h4>' + arr[arrayIndex].Group + '</h4><ul id="' + arr[arrayIndex].Group + '"></ul>';
        $('#container').append(content);
    }
}

for (var arrayIndex in arr)
{
    var list = '<li>' +
            '<input type="checkbox"  id="' + arr[arrayIndex].Group + '-' + arr[arrayIndex].Name + '" />' +
            '<label>' + arr[arrayIndex].Name + '</label>' + '</li>';

    $('#container > ' + '#' + arr[arrayIndex].Group).append(list);
}         
Sign up to request clarification or add additional context in comments.

Comments

1
        var content = '';
        var prev = '';

        for (var arrayIndex in arr) {

           if(prev != arr[arrayIndex][0])
           {
                prev = arr[arrayIndex][0];
                content  += '<h4>'+arr[arrayIndex][0]+'</h4><ul id="'+arr[arrayIndex][0]+'"></ul>';
               $('#container').append(content);
           }

        }

        for (var arrayIndex in arr) {

        var list = '<li>'+
                      '<input type="checkbox" name="'+arr[arrayIndex][1]+'" id="'+arr[arrayIndex][0]+'-'+arr[arrayIndex][1]+'" />'+
                      '<label>'+arr[arrayIndex][1]+'</label>'+
                  '<li>';

                  $('#'+arr[arrayIndex][0]+' > ul').append(list);

        }

try this . this should work , but i did not check the code , i think the logic is correct

Comments

0

check out Jquery Templates

http://api.jquery.com/tmplitem/

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.