6

I am building a list of checkbox items in jQuery based on an array returned from a handler.

The containing element is the .listContainer element below and then each dynamic element I want to add to this takes the form of the .listContainerItem element. Each item will have checkbox value and label based on the array item creating it.

<div class="listContainer">
    <div class="listContainerItem">
        <input type="checkbox" value="1" />
        <div class="listContainerItemLabel">Checkbox 1</div>
    </div>
</div>

At the point of the function that has the array passed to it, what is the most efficient way of creating this? I have been trying to accomplish it as below, but quickly running into major performance issues.

function AddItemToListContainer(item) {
    var currentItems = $j("#listContainerAvailable .listContainerItem");
    if ($j.grep(currentItems, function (e) { return $j(e).find(":checkbox:first").val() == item.Id; }).length === 0) {
        labelDiv = $j("<div />").addClass("listContainerItemLabel").html(item.Text);
        itemToAdd = $j("<div />").addClass("listContainerItem").append("<input type=\"checkbox\" value=\"" + item.Id + "\" />").append(labelDiv);
        currentItems.append(itemToAdd);
    }
}

I've looked at .map function, but not sure quite how to implement it. Can someone point me in the right direction?

3
  • 4
    As a note: .append("<input type=\"checkbox\" value=\"" + item.Id + "\" />") can be .append('<input type="checkbox" value="' + item.Id + '">') which is just easier to read and debug. Commented Mar 4, 2013 at 12:14
  • Do you get the list of items at once and can you replace the whole set of checkboxes or will it append only a few new at any time? Commented Mar 4, 2013 at 12:18
  • I have a separate function that first removes anything from the DOM that is not in the array, so all I need to then do is check that each item isn't already represented in the DOM and if not add it. Commented Mar 4, 2013 at 12:26

4 Answers 4

1

I would start with something like this:

var $container = $j('#listContainerAvailable');
var checkboxes = {};

function AddItemToListContainer(item) {
    if (checkboxes[item.Id]) return false;

    checkboxes[item.Id] = true;

    var $item = $j('<div />', {
        'class': 'listContainerItem',
    }).appendTo($container);

    $j('<input />', {
        'type': 'checkbox',
        'value': item.Id
    }).appendTo($item);

    $j('<div />',  {
        'class': 'listContainerItemLabel',
        'text': item.Text
    }).appendTo($item);
}

As long as none of these elements exist when you create the page, you can add them to a hash table instead of searching through the DOM. I think you'd also benefit from a JS templating engine like mustache.js

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

Comments

1

Are you wanting to have these elements appear one at a time? or just be dynamically created from an array on page load?

For the last:

html

    <div class="listContainer">
       <div class="listContainerItem"></div>
     </div>  

and jquery

var array = ['1', '2', '3', '4', '5'];

 $.each(array, function (index, value) {
    $(".listContainerItem").append('<input type="checkbox" value="' + value + '" /> <div         class="listContainerItemLabel">Checkbox ' + value + '</div>');
 });

http://jsfiddle.net/jeremythuff/HEKjk/

And some .click events can give you the first effect

Comments

1

When pressing the button of the code it will check if the input field has been filled in if it is empty it will alert you with a pop-up If it isnt empty it takes the value of the input field, create a checkbox and put the value of the input next to your checkbox.

HTML of the form

<form name="formName" id="listContainerItem">
    <input id="newinput" type="text" value=""/><button id="button">Add new rule</button> <br />
    <input type="checkbox" value="1" /><span class="listcontainerItemLabel" />Checkbox 1 <br />
</form>

Javascript

$(#button).click(function() {
function addLine(e) {
        e.preventDefault();
        var x = document.getElementById('newinput').value;
        if(x == '') {
            alert('not filled in')
        } else {
            $('#listContainer').append('<input type="checkbox" value="1" /><span class="listcontainerItemLabel" />'+x+  '<br />')
        }
    }

});

remember document.getElementById('newinput') can also be written like this: $('#newinput')

all you got to do is change what will be appended a bit with your needs.

Comments

0

You can use many ways to dynamically create....

$("#elementid").after("<input type='checkbox'></input><span></span>;

$("#elementid").before("<input type='checkbox'></input><span></span>;

$("#elementid").append("<input type='checkbox'></input><span></span>;

$("#elementid").prepend("<input type='checkbox'></input><span></span>;

like wise you can use insertAfter(), insertBefore(), appendTo(), prependTo().....

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.