Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Adding rows to a table

I'm completely new to JavaScript and jQuery and now I am trying to modify a html table.

Every time a button is clicked, the some stuff (input, text, button) should be added as the last row. I managed that for the first row, but when I click the button again, the next input will be added next to the last row and not under it. I don't understand why. Hope you can help.

This is my html file:

...
<main>
  <article id="main">
    ...
    <section id="neue vorschlaege">
      ...
      <table id="vorschlaege"> 
        <tr> 
          <td>Deine Idee</td>
          <td>Vorschläge</td>
          <td>Kategorie</td>
          <td>Löschen</td>
        </tr>
        <!-- I want to insert new rows here -->
      </table>
    </section>
  </article>
  ...
</main>

And this is my jQuery.js:

$(document).ready(function(){
  $('#abschicken').on('click', function(add){
    add.preventDefault();
    var name = $("#name").val();
    var fvv = $('input[name=FVV]:radio:checked').next('label:first').html();
    var zutaten = $("#zutaten").val();
    var passwort = $("#pw").val();

    $('#vorschlaege > tbody:last-child').append(
      '</tr>'
      +'<td><input type="checkbox" checked="true"></td>'
      +'<td>'+name+'</td>'
      +'<td>'+fvv+'</td>'
      +'<td><button id="loeschen">löschen</button></td>'
      +'</tr>');
  });
});
like image 535
SuperTasche Avatar asked Nov 23 '16 13:11

SuperTasche


People also ask

How do I add rows to a table?

Click in a cell above or below where you want to add a row. Under Table Tools, on the Layout tab, do one of the following: To add a row above the cell, click Insert Above in the Rows and Columns group. To add a row below the cell, click Insert Below in the Rows and Columns group.

How do you insert new row at a certain index in a table in jQuery?

The task is to insert a new row in that table at a certain index using JQuery. Approach: Store the table column value <td> element into the variable. Then use eq() and after() method to insert the row in a table.

How do I add a row to a table in button click?

To add a row, define a variable that keeps the count of the total number of that now exists in the table. Then we will use the jQuery “click” event to detect a click on the add row button and then use the . append() method of jQuery to add a row in the table.


1 Answers

You started with a </tr>closing tag.

$('#vorschlaege > tbody:last-child').append(
            '<tr>'// need to change closing tag to an opening `<tr>` tag.
            +'<td><input type="checkbox" checked="true"></td>'
            +'<td>'+name+'</td>'
            +'<td>'+fvv+'</td>'
            +'<td><button id="loeschen">löschen</button></td>'
            +'</tr>');
like image 51
PsyLogic Avatar answered Sep 18 '22 17:09

PsyLogic