0

I creating jquery code to generate specific html-blocks that contains html-controls (e.g. textbox, textarea, button) with two buttons - add new block and delete current block:

$(document).ready(function () {

    // Constants

    var SEPARATOR = "`";
    var SEPARATOR_START = "<span class='Hidden'>";
    var SEPARATOR_END = "</span>";
    var SEPARATOR_BLOCK = SEPARATOR_START + SEPARATOR + SEPARATOR_END;
    var CONTAINER = "#weContainer";

    // Initialize container
    InitializeDataContainer(CONTAINER);

    // Buttons events

    $(".AddBlock").click(function () {
        AddBlock(CONTAINER);
    });

    $(".DeleteBlock").click(function () {
        DeleteBlock(CONTAINER, GetParentId(this));
    });

    // Functions

    function GetParentId(container) {
        var id = ($(container).parent().attr("id")).replace(new RegExp("_", 'g'), "");
        return id;
    }

    function Template() {
        var uniqueId = Math.random() * 10000000;
        var template = "<div class='weBlock' id='_" + uniqueId + "_'>";
        template += "<input type='button' value='add' class=\"AddBlock\" />";
        template += "<input type='button' value='del' class=\"DeleteBlock\" />";
        template += "<br/>";
        template += "<input type='text' class='weStartDate weTextbox' />";
        template += "&nbsp;&nbsp;";
        template += "<input type='text' class='weEndDate weTextbox' />";
        template += "<br/>";
        template += "<input type='text' class='weCompany weTextbox' />";
        template += "&nbsp;&nbsp;";
        template += "<input type='text' class='weJobTitle weTextbox' />";
        template += "<br/>";
        template += "<input type='text' class='weClients weTextbox' />";
        template += "&nbsp;&nbsp;";
        template += "<input type='text' class='weProjectName weTextbox' />";
        template += "<br/>";
        template += "<textarea type='text' rows='4' cols='40' class='weProjectDesc weTextarea'></textarea>";
        template += "<br/>";
        template += "<textarea type='text' rows='6' cols='40' class='weActivities weTextarea'></textarea>";
        template += "<br/>";
        template += "<textarea type='text' rows='4' cols='40' class='weToolsTech weTextarea'></textarea>";
        template += "</div>";
        template += SEPARATOR_BLOCK;
        return template;
    }

    function GetIdFromTemplate(template) {
        var array = template.split('_');
        return array[1];
    }

    function AddBlock(container) {
        $(container).append(Template());
    }

    function DeleteBlock(container, id) {
        var content = $(container).html();
        content = content.replace(new RegExp("\<span class='Hidden'\>", "g"), "")
            .replace(new RegExp("\</span\>", "g"), "");
        var blocks = content.split(SEPARATOR);
        content = "";
        var index;
        for (var i = 0; i < blocks.length; i++) {
            if (GetIdFromTemplate(blocks[i]) != id && !IsNullOrEmpty(blocks[i])) {
                content += blocks[i] + SEPARATOR_BLOCK;
            }
            else {
                index = i;
            }
        }
        $(container).html(content);
    }

    function IsNullOrEmpty(string) {
        if (string == null || string == 'undefined' || string.length == 0) {
            return true;
        }
        else {
            return false;
        }
    }

    function InitializeDataContainer(container) {
        $(container).html(Template());
    }
});

For the first time (when page load) i created first block:

function InitializeDataContainer(container) {
        $(container).html(Template());
    }

My problem is next - buttons Add and Delete work only for this first html-block that i created when page load, but if i add new blocks in page using Add button (from this first block that works) then buttons Add and Delete from this new blocks doesn't work! Sorry for may be not good code, im not javascript engineer:)

1
  • 2
    I don't see anything dynamic in your template except uid - why not just keep this in pure html, clone and set proper uid? Commented Aug 4, 2011 at 11:12

2 Answers 2

4

Use the .live() instead:

$(".AddBlock").live("click", function () {
    AddBlock(CONTAINER);
});

And same for the other class - the .click() is "static" only for the elements that exists in the time of calling it, while .live() should work for any existing or future elements.

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

Comments

2

Your jQuery code adds event handlers to the Add/Delete buttons you create uses click to do so:

$(".AddBlock").click(function () {
    AddBlock(CONTAINER);
});

This only affects HTML elements that are already in the page.

One solution would be to change it to

$(".AddBlock").live('click', function () {
    AddBlock(CONTAINER);
});

to make it also work for elements that get added to the page later.

Another solution would be to manually add the click event handlers to any elements you add to the page dynamically:

function AddBlock(container) {
    var $template = $(Template());
    $(container).append($template);
    $template.find(".AddBlock").click, function () {
        AddBlock(CONTAINER);
    });
    $template.find(".DeleteBlock").click, function () {
        DeleteBlock(CONTAINER, GetParentId(this));
    });
}

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.