0

I need to make one thing 1)Create or Delete Rows. Errors Found the genereted rows don't execute the buttons actions add or delete (not coded), I'm using the same attributes used in the original buttons.I dont know why is this happening, the append method dont clone the rows values ?who other do it?

  <table class="tabla_uno table table-hover">
    <thead>
      <tr>
        <th >#</th>
        <th >First Name</th>
        <th >Last Name</th>
        <th >Username</th>
        <th ></th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>a</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td class="controls">
          <button class='boton_mas btn btn-success btn-sm'>+</button>
          <button class='boton_menos btn btn-danger btn-sm'>-</button>
        </td>
      </tr>
      <tr>
        <td>b</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td class="controls">
          <button class='boton_mas btn btn-success btn-sm'>+</button>
          <button class='boton_menos btn btn-danger btn-sm'>-</button>
        </td>
      </tr>
    </tbody>

  </table>
  <hr>

  <script>
    $(document).ready(function() 
    {
// ADD
  $(document).on("click", ".boton_mas",function()
  {
    var datos = $(".tabla_uno tbody tr:first").clone();
    $("#product").append($(this).html());
    var insertHere = $(this).closest("tr");
    datos.insertAfter(insertHere);
  })

  // REMOVE
  $(document).on("click", '.boton_menos', function() 
  {
    var rowCount = $('.tabla_uno tbody tr').length;
    var MinRwows = 1;        
    if (rowCount === MinRwows)
    {
      alert("Minimo alcanzado, no puedes borrar mas filas");          
    }
    else
    {
      $(this).closest("tr").remove();
    }
  })
  }) 

2 Answers 2

2

This does what you seem to be looking for. You'll want to populate the new rows differently, of course, but it'll get you closer.

Note that I had to add the event listener to the document itself, rather than listening for the selector directly. This is because of the dynamically created elements -- the event listeners defined before they're created don't catch them.

$(document).ready(function() {


  /*****
   * This function will add a row to the given table directly
   *   after the row containing the clicked plus button. It will
   *   clone the first table row each time, then empty it of all
   *   data, then insert it into the given location.
   *****/
  $(document).on("click", '.boton_mas', function() {
    // Find the first table body row, and clone it.
    var datos = $(".tabla_uno tbody tr:first").clone();

    // Replace the row number with the newly obtained number.
    datos.find("th").empty();

    // Stick dummy content into the clone's td's.
    datos.find("td").not(".controls").each(function() {
      $(this).text($(this).index());
    });

    // Locate the row that was clicked. We'll add right after this.
    var insertHere = $(this).closest("tr");

    // And stick the new row in.
    datos.insertAfter(insertHere);
    
    // Hide the control buttons...
    datos.find(".boton_mas, .boton_menos").hide();
    
    // Now, we need to re-index all the rows headers:
    $(".tabla_uno tbody th").each(function(){
      // get the index of the row itself, increment it by one
      //   as indices are zero-based, and change the th text.
      $(this).text(parseInt($(this).closest("tr").index()) +1);
    })
  }) // end .on("click", ".boton_mas")

  /****
   * This function will remove rows when the minus button has
   *  been clicked. It will only run when there are more than 
   *  one row, otherwise, it will do nothing.
   ****/
  $(document).on("click", '.boton_menos', function() {
    // This if statement will force a minimum of one row.
    if($(".tabla_uno tbody tr").length > 1){
      // Simply remove the ancestor TR containing this 
      $(this).closest("tr").remove();
    
    }
  }) // end .on("click", ".boton_menos")
  
  // Utility functions to hide and show the add/remove buttons.
  //  Note that these expect that the css was used to hide them.
  $(document).on("mouseenter",".tabla_uno tbody tr", function(){
    // Row is hovered, show the buttons.
    $(this).find(".boton_mas, .boton_menos").show();
  }).on("mouseleave", ".tabla_uno tbody tr", function(){
    // Row is no longer hovered, hide them again!
    $(this).find(".boton_mas, .boton_menos").hide();
  });
})
.boton_mas, .boton_menos {
  display: none;
}

tr {
  height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tabla_uno table table-hover">
  <thead>
    <tr>
      <th>#</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Username</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
      <td class="controls">
        <button class='boton_mas btn btn-success btn-sm'>+</button>
        <button class='boton_menos btn btn-danger btn-sm'>-</button>
      </td>
    </tr>
    <tr>
      <th>2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
      <td class="controls">
        <button class='boton_mas btn btn-success btn-sm'>+</button>
        <button class='boton_menos btn btn-danger btn-sm'>-</button>
      </td>
    </tr>
    <tr>
      <th>3</th>
      <td>Larry the Bird</td>
      <td> Bird</td>
      <td>@twitter</td>
      <td class="controls">
        <button class='boton_mas btn btn-success btn-sm'>+</button>
        <button class='boton_menos btn btn-danger btn-sm'>-</button>
      </td>
    </tr>
  </tbody>
</table>

So, to make the insert work as you'd like (where the new row is added immediately following the clicked row), simply find the TR that contains the clicked element and use datos.insertAfter(insertHere); as you can see in the above code.

So there were two more changes you wanted made, to fit your case. Both pretty trivial, both pretty reasonable. If you look at the end of the '.boton_mas' function, you'll see an .each() loop that reindexes all rows when a row is added. You're absolutely right in your comment, we don't need to sum rows, simply need to reindex the entire thing. Easily done, check the loop.

The other change, to force one or more rows (so NOT allowing the last remaining row to be deleted) is simply done by adding the if statement, as I did in the '.boton-menos' function. That checks first to see if there is more than one row remaining and, if there is, doing the processing of removing the clicked row. Otherwise, the if is bypassed and the row is untouched.

Also, added the third functionality you were looking for, missed the comment regarding hiding/showing the add/remove buttons unless the row was being hovered. You'll see them at the end of the code block, commented as usual.

Hope this helps!

Sign up to request clarification or add additional context in comments.

15 Comments

hello snowmonkey, your code work, but i need to add the row next to the button i pushed(lets say i press 1 - Mark), the rows must to be next to it. And the buttons has to be hide when the mouse is not on the rows
@fsnfusion, Try it now. I've made the change to handle this.
Good Morning Snowmonkey. Thats it !... The only thing it need is the buttons show only when the mouse hover the td, can i vote for you after that or now?
Another thing i saw in your code is, we can remove all rows, thats not right, we need to make a limit, min 1 row
another thing i saw, theres no need to sum the rows, its only add or remove one at the desired position
|
1

$(".tabla_uno").on('click','.boton_mas',function()
	{						
          let TR=$("<tr/>");          
          let TD1=$("<td/>",{text:'1'});
          let TD2=$("<td/>",{text:'2'});
          let TD3=$("<td/>",{text:'3'});
          let TD4=$("<td/>",{text:'4'});
          let TDBTN=$("<td/>");
          let BTN_mas=$("<button/>",{class:'boton_mas btn btn-success btn-sm',text:'+'});
          let BTN_menos=$("<button/>",{class:'boton_menos btn btn-danger btn-sm',text:'-'});
          TR.append(TD1);
          TR.append(TD2);
          TR.append(TD3);
          TR.append(TD4);
          TDBTN.append(BTN_mas);
          TDBTN.append(BTN_menos);
          TR.append(TDBTN);
	  $(".tabla_uno tbody").append(TR);
	});
     $(".tabla_uno").on('click','.boton_menos',function()
      {
        $(this).parent().parent().remove();   
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tabla_uno table table-hover">
  <thead>
    <tr>
      <th>#</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Username</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
      <td>
<button class='boton_mas btn btn-success btn-sm'>+</button>
<button class='boton_menos btn btn-danger btn-sm'>-</button>
      </td>
    </tr>
    <tr>
      <th >2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
      <td>
<button class='boton_mas btn btn-success btn-sm'>+</button>
<button class='boton_menos btn btn-danger btn-sm'>-</button>      	
      </td>
    </tr>
    <tr>
      <th >3</th>
      <td>Larry the Bird</td>
      <td> Bird</td>
      <td>@twitter</td>
      <td>
<button class='boton_mas btn btn-success btn-sm'>+</button>
<button class='boton_menos btn btn-danger btn-sm'>-</button>      	
      </td>
    </tr>
  </tbody>
</table>

8 Comments

seems okay. But you need to include jQuery library in your html.
Try removing the rows you've just added -- the event listener is not bound to them.
Do not you want to use jQuery?
There you go. The $(document).on(...) does listen to dynamic events. Looks good.
Now the only thing i don't care for about this, and the original, is that the row being created is hard-coded in. By cloning one of the existing rows, and simply replacing all the appropriate content, my controls don't run the risk of breaking.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.