Jquery Append Method

1

Greetings, I'm doing this append.

$(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td><button class='tiempo_plan_boton_menos'>+</button><button>-</button></td>");

The question is that the attribute that I am adding to the button seems not to be active, since at the moment of clicking on the button, nothing happens. Why is this behavior?

This is the click event

$(".tiempo_plan_boton_mas").click(function()
{
    $(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td><button class='tiempo_plan_boton_mas'>+</button><button>-</button></td>");
})

The table

    <table id="table1" class="table table-sm table-bordered table-hover">
    <thead class="thead-light">
    <tr>
    <th rowspan="2">Etapa</th>
    <th rowspan="2">Actividad</th>
    <th>Tiempo</th>
    <th colspan="2">Tiempo Parcial Acumulado</th>
    <th>Tiempo Total Acumulado</th>
    <th>Acciones</th>
    </tr>
    <tr>
    <td>Hora</td>
    <td>Hora</td>
    <td>Dias</td>
    <td>Dias</td>                                           
</tr>                                           
    </thead>
    <tbody>
    <tr>
    <td ></td>
    <td ></td>
    <td ></td>
    <td ></td>
    <td ></td>
    <td ></td>
    <td >
    <button class='tiempo_plan_boton_mas btn btn-success btn-sm'>+</button>
    <button class='tiempo_plan_boton_menos btn btn-danger btn-sm'>-</button>
    </td>
    </tr>
    <tr>
    <td ></td>
    <td ></td>
    <td ></td><td ></td>
    <td ></td>
    <td ></td>
    <td >
    <button class='tiempo_plan_boton_mas btn btn-success btn-sm'>+</button>
    <button class='tiempo_plan_boton_menos btn btn-danger btn-sm'>-</button>
    </td>
    </tr>   
    </tbody>
    </table>
    
asked by Alex Hunter 12.12.2017 в 15:46
source

2 answers

2

First of all you must change your selector:

$(".tiempo_plan_boton_mas").click(function(){
    $(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td><button class='tiempo_plan_boton_mas'>+</button><button>-</button></td>");
})

For this other:

$(document).on('click', '.tiempo_plan_boton_mas', function(){
    $(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td><button class='tiempo_plan_boton_mas'>+</button><button>-</button></td>");
})

The difference is that in the second selector you are selecting the document first and you are indicating that you look for an element (inside the document) and apply the event click , while in the first selector you are directly accessing an element that when the JS was loaded, it did not exist, that's why it does not work for you.

Now talking about your code you have a logic error because when doing a .after() you are adding the <td> after the <tr> then when clicking the buttons created they will never find a parent element <tr> why nothing is executed.

With this in mind let's add several <tr> to your <tbody> **

$(document).on('click', '.tiempo_plan_boton_mas', function(){
    $(this).closest('tr').css("background", "cyan").after("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td><button class='tiempo_plan_boton_mas'>+</button><button>-</button></td></tr>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
    <thead>
        <tr>
            <th>Item</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
            <td>6</td>
            <td>
                <button class='tiempo_plan_boton_mas'>+</button>
                <button>-</button>
            </td>
        </tr>
    </tbody>
</table>
    
answered by 12.12.2017 / 16:44
source
1

Friend that is a very common problem when you update the DOM instead of using the event click() of jquery use the event on() that as a parameter receives another event.

change your code

 $(".tiempo_plan_boton_mas").click(function()
 {
  $(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td>
   <td>3</td><td>4</td><td>5</td><td>6</td><td><button 
   class='tiempo_plan_boton_mas'>+</button><button>-</button></td>");
  })

for this to see if it works for you

$(document).on("click",".tiempo_plan_boton_mas",function()
 {
  $(this).closest('tr').css("background","cyan").after("<td>1</td><td>2</td>
   <td>3</td><td>4</td><td>5</td><td>6</td><td><button 
   class='tiempo_plan_boton_mas'>+</button><button>-</button></td>");
  })

The on() event causes all the html to be traversed within an object and so we can use the dynamic html that we bring after rendering the page for the first time.

I hope you help greetings.

Definition and use

  

The on () method connects one or more event handlers for the selected elements and child elements.

     

As of jQuery version 1.7, the on () method is the new replacement for the bind (), live (), and delegate () methods. This method brings a lot of consistency to the API, and we recommend that you use this method, since it simplifies the code base of jQuery.

     

Note: Event handlers attached using the on () method will work for current and FUTURE elements (such as a new element created by a script).

     

Tip: To remove event handlers, use the off () method.

     

Tip: To attach an event that only runs once and then is deleted, use the one () method.

Syntax

$(selector).on(event,childSelector,data,function,map)

Source : www.w3schools.com

var root = 'https://jsonplaceholder.typicode.com';
$(".botonTraeHtml").click(function(){
$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  $(".contenedorhtmlNuevo").html("<p>Este boton no va a funcionar porque usa la funcion normal click que no se ejecuta con html dinamico</p><button class='btnClickNormal' type='button' name='button'>Boton dinamico con evento click normal</button><br><br><p>Este boton si va a funcionar porque tiene la funcion on que ejecuta html dinamico</p><button class='btnClickOn' type='button' name='button'>Boton dinamico con evento On</button>")

});
})

//evento click normal que solo funciona con html no dinamico
$(".btnClickNormal").click(function(){
  alert("hola soy un boton traido dinamicamente")
})

//evento on click que funciona con cualquier html dinamico o no
$(".contenedorhtmlNuevo").on("click",".btnClickOn",function(){
  alert("hola soy un boton traido dinamicamente")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="botonTraeHtml" type="button" name="button">Traer html dinamico</button>

<div class="contenedorhtmlNuevo">
    
  </div>

In your case what you want is to add a tr to a table and delete it I leave you an example I hope it is what you need

To add an element before use the function after and in this example we first get the event click after with the parents("tr") we go to the father tr and we add the new element before the.

$("#table1").on("click",".btn-agregar",function(){
 $(this).parents("tr").after("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td><button class='btn-agregar' type='button' name='button'>+</button><button class='btn-eliminar' type='button' name='button'>X</button></td></tr>").css({"background": "rgb(54, 207, 87)"})
})


//usamos el metodo on para los botones de los tr dinamicos para que pueda funcionar el evento click
$("#table1").on("click",".btn-eliminar",function(){
 $(this).parents("tr").remove()
})
*{
  font-family: arial;
  margin: 0px;
  padding: 0px;
}
table thead {
  background: rgb(228, 228, 228);
}
table thead th {
  padding: 10px;
}
table tr {
background: rgb(186, 186, 186);
}

table td {
  
  text-align: center;
}
table td button {
  padding: 10px;
}
button {
  padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
    <thead>
      <tr>
        <th>valor1</th>
        <th>valor2</th>
        <th>valor3</th>
        <th>valor4</th>
        <th>valor5</th>
        <th>Agregar/Eliminar</th>
      </tr>
    </thead>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td><button class='btn-agregar' type='button' name='button'>+</button><button class='btn-eliminar' type='button' name='button'>X</button></td></tr>
    </tbody>
  </table>
    
answered by 12.12.2017 в 16:44