Rafael MosMad
Rafael MosMad

Reputation: 3

jQuery - Add click event to a dynamically created element

I have dynamically created this elements clicking the #btnAgregar button:

var items = 0

$("#btnAgregar").click(function(){

  items = items + 1

  var item_name =  $("#itemLista").val();

  var $div_task = $("<div/>", { class: "div_task" }),
      $div_task_nombre = $("<div/>", { class: "div_task_nombre" }),
      $div_task_edicion = $("<div/>", { class: "div_task_edicion" }),
      $div_task_nombre_item = $("<p/>", {class: "item task_undone", text: item_name}),
      $div_task_edicion_btnEliminar = $("<button/>", {class: "btn btn-danger", type: "button", id: items}),
      $div_task_edicion_btnEliminar_span = $("<span/>", {class:"glyphicon glyphicon-minus"});

  $div_task.append(
                  $div_task_nombre.append(
                                          $div_task_nombre_item
                                        ), 
                  $div_task_edicion.append(
                                            $div_task_edicion_btnEliminar.append($div_task_edicion_btnEliminar_span)
                                          )
                  ).appendTo("#container_lista");

});

This code works fine.

I need to add a click event to the element "#btnEliminar"+items

If I do this, the code doesn't work:

$('body').on('click', '#'+items, function() {
  //Do something
});

But if I just add the id "#1" (first element created) it works fine.

Ej:

$('body').on('click', '#1', function() {
  //Do something
});

Can you help me?

Upvotes: 0

Views: 76

Answers (2)

Andy Fleming
Andy Fleming

Reputation: 7875

You want to bind the event to the document or 'body' or something similar. If you want match dynamically-numbered elements, you can use a selector like div[id^="example"] to match any ID that starts with example like <div id="example1"> and <div id="example2">.

$(document).on('click', 'div[id^="example"]', function() {
    console.log('element clicked');
});

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

Can add it right to the object as you create it, or add another class that is specific to that type of button.

Using class = btnEliminar:

$('body').on('click', '.btnEliminar', function() {
  alert(this.id.replace('btnEliminar','');
});

you only need to run this code once within your page load code

Upvotes: 1

Related Questions