0

Hello I'm trying to call to a function when one make a click on some elements.

I'm doing a form using symfony php framework. Following this: http://symfony.com/doc/current/cookbook/form/form_collections.html#template-modifications

I readed this: https://stackoverflow.com/a/1207393/4386551

But it does not work with a.delete elements, it works for a.add only.

var $collectionHolder;

// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add">Add a tag</a>');
var $newLinkLi = $('<li></li>').append($addTagLink);

jQuery(document).ready(function() {
    // Get the ul that holds the collection of tags
    $collectionHolder = $('ul.details');

    // add the "add a tag" anchor and li to the tags ul
    $collectionHolder.append($newLinkLi);

    // count the current form inputs we have (e.g. 2), use that as the new
    // index when inserting a new item (e.g. 2)
    $collectionHolder.data('index', $collectionHolder.find(':input').length);

    $addTagLink.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addTagForm($collectionHolder, $newLinkLi);
    });
    $(".details").on("click", "a.add", function (){alert("HEY");});
    $(".details").on("click", "a.delete", function (){alert("HEY");});

});

function addTagForm($collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = $collectionHolder.data('prototype');

    // get the new index
    var index = $collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    $collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('<li></li>').append(newForm);
    $newLinkLi.before($newFormLi);
    addTagFormDeleteLink($newFormLi);

}

function addTagFormDeleteLink($tagFormLi) {
    var $removeFormA = $('<a href="#" class="delete">delete this tag</a>');
    $tagFormLi.append($removeFormA);

    $removeFormA.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // remove the li for the tag form
        $tagFormLi.remove();
        //reload_total();

    });
}

what's wrong with a.delete and jquery.on?

Community
  • 1
  • 1

1 Answers1

0

Try to change to:

$(".details a.add").on("click", function (){alert("HEY");});
$(".details a.delete").on("click", function (){alert("HEY");});

Or this:

$(".details").on("click", "a.add, a.delete", function (){alert("HEY");});
Berriel
  • 12,659
  • 4
  • 43
  • 67