0

I am writing a script that clones the content of a specified div when a button is clicked. The script will add a button specified in the HTML that will remove the content that is cloned. My problem is that when this new button is clicked, I can't simply add an event function to that dynamic button. I currently have to add an onclick property in the HTML. What I want to do is instead of using onclick="remove();", to use rel="remove" and then add the event to any element with that rel.

My Current HTML:

<div id="references-content"><!-- The content to duplicate.... excludes the parent div tag i.e. only the input tag. -->
    <input type="text" name="references[]" size="30"  class="text-input" placeholder="Must contain a valid, working URL." style="position: relative;z-index: 0;">                               
</div>
<!-- Where to put the new content -->
<div id="more-references">
</div>
<div id="remove-button" style="visibility: hidden;">
     <i class="fi-x" style="cursor: pointer;padding: 10px;" onclick="removeThis(this);"></i> <!-- This element should use rel="removeThis" instead of onclick -->
</div>      
<i class="fi-plus" rel="addMore" id="references" style="cursor: pointer;"></i><!-- The button that adds content -->

My Current jQuery

$(function(){

    var i = 0;

    var oldRemove = $('#remove-button');

    $('[rel="addMore"]').on('click', function(){

        i++;

        var newRemove = oldRemove.clone();

        var buttonID = $(this).attr("id");
        var container = $('#' + buttonID + '-content');
        var content = container.html();
        var insertionPoint = $('#more-' + buttonID);

        insertionPoint.append('<div id="' + buttonID + '-' + i + '">' + content + newRemove.html() + '</div>'); 

    });

});

function removeThis(elem){

    $(elem).parent().remove();

}

The jQuery that I would like that doesn't seem to work:

$(function(){

    var i = 0;

    var oldRemove = $('#remove-button');

    $('[rel="addMore"]').on('click', function(){

        i++;

        var newRemove = oldRemove.clone();

        var buttonID = $(this).attr("id");
        var container = $('#' + buttonID + '-content');
        var content = container.html();
        var insertionPoint = $('#more-' + buttonID);

        insertionPoint.append('<div id="' + buttonID + '-' + i + '">' + content + newRemove.html() + '</div>'); 

    });

    $('[rel="removeThis"]').on('click', function(){

        $(this).parent().remove();

    });

});
ShoeLace1291
  • 4,551
  • 12
  • 45
  • 81
  • Try binding to the document instead, something like this perhaps? `$(document).on('click', '[rel="addMore"]', function(){` – mituw16 May 14 '14 at 19:09
  • An answer to this question can already be found on SO. See http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – filoxo May 14 '14 at 19:09

0 Answers0