Convert dynamic element into clickeable

2

I have the following element in my project:

Individual code for each box

<div class="col-md-3 col-sm-6 col-xs-12">
          <div class="info-box bg-aqua">
            <span class="info-box-icon"><i class="fa fa-bookmark-o"></i></span>

            <div class="info-box-content">
              <span class="info-box-text">Caja</span>
              <span class="info-box-number">41,410</span>

              <div class="progress">
                <div class="progress-bar" style="width: 70%"></div>
              </div>
                  <span class="progress-description">
                    70% Increase in 30 Days
                  </span>
            </div>
            <!-- /.info-box-content -->
          </div>
          <!-- /.info-box -->
        </div>

The issue is that the sample depending on the box number, can be 1 or 1000, the question is that I want to return the element clickable as a <a href=""> but that does not direct me to any page but that I do an action like is DEPENDING which box clickee:

$(".caja1").click(function() {
    console.log("Clickeo la caja # X");
});

How can I re-click the element and at the same time in javascript know which element to click?

Thank you very much for the help.

EDITED

Updated code to the answers but does not throw anything (Affect that is showing dynamically in the operation of .click()... ?)

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

    var valor = document.getElementById("loteBuscar").value;
    var totalCajas;
    var iter = [];
    $.ajax({
        url: "views/ajax/OIT.php",
        method: "GET",
        data: { funcion: "funcion6", box: valor },
        async: false,
        dataType: "json",
        success: function(respuesta) {
            totalCajas = respuesta.cantidadCajas;
            //console.log(respuesta.cantidadCajas);
            for (var i = totalCajas; i > 0; i--) {
                $(".contenedorCajas").append('<div class="col-md-3 col-sm-6 col-xs-12 cajas" id="' + (i - 1) + '"><div class="info-box bg-aqua"><span class="info-box-icon"><i class="fa fa-cube"></i></span><div class="info-box-content"><span class="info-box-text">Caja ' + (i - 1) + '</span><span class="info-box-number">41,410</span><div class="progress"><div class="progress-bar" style="width: 70%"></div></div><span class="progress-description">70% Increase in 30 Days</span></div><!-- /.info-box-content --></div><!-- /.info-box --></div>');
            }
        }
    });
});

$(".cajas").click(function() {
    console.log($(this.id));
});
    
asked by Baker1562 18.02.2018 в 19:23
source

2 answers

4

You can create a general class for all the boxes and listen to the event for that class. After the event is given if for example we want the title of the box we use find to find the class .info-box-text the same would work for another class that is inside the box as .info-box-number

As you add the elements in the DOM, you have to assign the listener to an element that exists in the DOM, as in the case of document . $(document).on('click','.caja',function() { ... }

$(document).on('click','.caja',function() {
    //$(this) hace referencia al div con la clase caja que se clickeo
    console.log($(this).find('.info-box-text').text());
    console.log($(this).find('.info-box-number').text());
    //Si desea obtener el id
    console.log("ID " + this.id);
    // Puede agrear más funcionalidad o acción a realizar
});
.caja{
  background : #ccc;
  margin :2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<div class="col-md-3 col-sm-6 col-xs-12 caja"  id="caja1">
  <div class="info-box bg-aqua">
    <span class="info-box-icon"><i class="fa fa-bookmark-o"></i></span>

    <div class="info-box-content">
      <span class="info-box-text">Caja 1</span>
      <span class="info-box-number">41,410</span>

      <div class="progress">
        <div class="progress-bar" style="width: 70%"></div>
      </div>
          <span class="progress-description">
            70% Increase in 30 Days
          </span>
    </div>
  </div>
</div>

<div class="col-md-3 col-sm-6 col-xs-12 caja" id="caja2">
  <div class="info-box bg-aqua">
    <span class="info-box-icon"><i class="fa fa-bookmark-o"></i></span>

    <div class="info-box-content">
      <span class="info-box-text">Caja 2</span>
      <span class="info-box-number">42,110</span>

      <div class="progress">
        <div class="progress-bar" style="width: 70%"></div>
      </div>
          <span class="progress-description">
            70% Increase in 30 Days
          </span>
    </div>
  </div>
</div>
  

In my example, I use the class box in the singular. I should modify this already   that in your edited question use cajas

    
answered by 18.02.2018 / 19:36
source
2

You could add a class to each of your boxes and, using the reserved word this , get for example the id of each box.

The reserved word this refers to the element with which you are interacting at all times.

Get value when you dynamically generate the elements - Events delegate

As you are adding the elements dynamically using the function .append() of JQuery you will need to use a delegate event, which you can generate by means of the function .on() of JQuery.

I will indicate several phrases taken from the JQuery documentation itself:

  

Event handlers are linked only to currently selected items; they must exist at the moment when your code makes the call to .on () .

That is, if we were to call the JQuery .on() method as usual (directly to the .caja class), we would have to add all the elements using the .append() function before calling the .on() method .

Example calling the .on() method after adding the elements:

$("#cajas").append("<div id='caja1' class='caja'></div>");
$("#cajas").append("<div id='caja2' class='caja'></div>");
$("#cajas").append("<div id='caja3' class='caja'></div>");

$(".caja").on('click', function(){
  console.log("Clickeo la caja: " + this.id);
});
.caja{
   display: inline-block;
   height: 200px;
   width: 200px;
   background-color: red;
   margin: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cajas"></div>

Example calling the .on() method before adding the elements:

$(".caja").on('click', function(){
  console.log("Clickeo la caja: " + this.id);
});

$("#cajas").append("<div id='caja1' class='caja'></div>");
$("#cajas").append("<div id='caja2' class='caja'></div>");
$("#cajas").append("<div id='caja3' class='caja'></div>");
.caja{
   display: inline-block;
   height: 200px;
   width: 200px;
   background-color: red;
   margin: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cajas"></div>

As you can see, in this second example, as mentioned in the documentation, the event can not be launched when the elements are added after having made the .on() method call.

To do this, you will need to use delegate events . According to the documentation:

  

Delegate events have the advantage that they can process descendant element events that are added to the document later .

That is, we can add an event handler to the parent element but, in turn, it will process an event in case we have added a descendant element to it.

To create a delegate event, the structure would look like this:

$(referencia a elemento padre).on('click', referencia a elemento hijo, function(){
    //Código aquí
});

We could refer to document as a parent element but I preferred to add a container to the boxes because this way, in case you had other elements with the class .caja out of this container and you did not want to add them said event, it would not apply to them.

I leave an example applying all the above:

$("#cajas").on('click', '.caja', function(){
  console.log("Clickeo la caja: " + this.id);
});

$("#cajas").append("<div id='caja1' class='caja'></div>");
$("#cajas").append("<div id='caja2' class='caja'></div>");
$("#cajas").append("<div id='caja3' class='caja'></div>");
.caja{
   display: inline-block;
   height: 200px;
   width: 200px;
   background-color: red;
   margin: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cajas"></div>
    
answered by 18.02.2018 в 19:35