Problem closing tag with jquery (prepend, before)

0
$.each( elements, function(i, val){
    $('#tbl').prepend('<tr>').addClass('tr');
        $('.tr').before('<td>'+(i+1)+'</td><td>'+$(val).val()+'</td>');
           $('#tbl').prepend('</tr>');

});

alements comes from an input set of a form

The tr remains open

when adding new data are traversed in the same row

    
asked by matteo 17.07.2018 в 20:59
source

1 answer

1

Instead of using prepend , you can use appendTo . In addition, before adds the elements before the selected element. Instead you can use append . Here is an example:

$("#Add").on('click', function add() {
  var elements = $('input');
  $.each( elements, function(i, val){
    var tr = $('<tr></tr>').appendTo('#tbl');    
    tr.addClass('tr');
        tr.append('<td>'+(i+1)+'</td><td>'+$(val).val()+'</td>');           

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl"></table>
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
<button id="Add">Add</button>
    
answered by 17.07.2018 в 21:12