Stewart Alan
Stewart Alan

Reputation: 1643

Dynamically creating elements using jQuery

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?

Upvotes: 6

Views: 4541

Answers (4)

Ganesh Gaxy
Ganesh Gaxy

Reputation: 57

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().....

Upvotes: 0

Matthias Wegtun
Matthias Wegtun

Reputation: 1261

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.

Upvotes: 1

Jeremythuff
Jeremythuff

Reputation: 1548

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

Upvotes: 1

Blender
Blender

Reputation: 298562

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

Upvotes: 1

Related Questions