Add and Remove elements of the table using array in JQuery - javascript

This is my index and js file. When I click on the first table row it works but when I click on it again, it doesn't work. It works only one time for one table. Same thing is happening in the second table. I have also given the class name in the js file. Why it does not consider class name. Please explain it also.
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row, tr) {
t2[row] = $(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row, tr) {
t1[row] = $(tr).find('td:eq(0)').text()
});
$(".addRow").on("click", function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(), t1), 1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$(".deleteRow").on("click", function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(), t2), 1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
>
</script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>

Attach event (click) by using jQuery's .on(). Some possible changes you can make:
$("tbody").on("click",".addRow", function() {......
And
$("tbody").on("click",".deleteRow", function() {......
Also I think you are mistakenly adding class="addRow" instead of class="deleteRow" in the second for loop of .deleteRow click in the second table:
var tr = $('<tr class="deleteRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row,tr){
t2[row]=$(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row,tr){
t1[row]=$(tr).find('td:eq(0)').text()
});
$("tbody").on("click",".addRow", function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(),t1),1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for(var i = 0;i < t2.length;i++){
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for(var i = 0;i < t1.length;i++){
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$("tbody").on("click",".deleteRow", function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(),t2),1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for(var i = 0;i < t1.length;i++){
var tr = $('<tr class="addRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for(var i = 0;i < t2.length;i++){
var tr = $('<tr class="deleteRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">></script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>

In your code you are not specifying the selector in .on() function.
If selector is omitted or is null, the event handler is referred to
as direct.
When a selector is provided, the event handler is referred to as
delegated.
An event-delegation (direct) approach attaches an event handler to
only one element, the tbody.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
So you need to provided a selector for .on() function as below.
$('.table1').on('click', '.addRow', function() {})
$('.table2').on('click', '.deleteRow', function() {})
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time.
Source: http://api.jquery.com/on/
Also, you have an error in deleteRow functionality and fixed in below complete example.
var t1 = [];
var t2 = [];
$('.table2 tr').each(function(row, tr) {
t2[row] = $(tr).find('td:eq(0)').text()
});
$('.table1 tr').each(function(row, tr) {
t1[row] = $(tr).find('td:eq(0)').text()
});
$('.table1').on('click', '.addRow', function() {
var $delete = $(this).find("td:eq(0)").text();
t2.push($delete);
t1.splice($.inArray($(this).find("td:eq(0)").text(), t1), 1);
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
});
$('.table2').on('click', '.deleteRow', function() {
var $add = $(this).find("td:eq(0)").html();
t1.push($add);
t2.splice($.inArray($(this).find("td:eq(0)").text(), t2), 1);
var tbody1 = $('.body1');
$(".table1 tr").remove();
for (var i = 0; i < t1.length; i++) {
var tr = $('<tr class="addRow" style="color:#32c24d;cursor:pointer"/>').appendTo(tbody1);
tr.append('<td>' + t1[i] + '</td>');
}
var tbody2 = $('.body2');
$(".table2 tr").remove();
for (var i = 0; i < t2.length; i++) {
var tr = $('<tr class="deleteRow" style="color:#f44336;cursor:pointer"/>').appendTo(tbody2);
tr.append('<td>' + t2[i] + '</td>');
}
});
<!DOCTYPE html>
<html>
<head>
<title>Table Manipulation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
>
</script>
</head>
<body>
<div class="row">
<div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 available">
<label>Available Members</label>
<table class="table table-bordered table1">
<tbody class="body1">
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Tabrez</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Akash</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Keshav</td>
</tr>
<tr class="addRow" style="color:#32c24d;cursor:pointer">
<td>Harsh</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-4 col-md-4 selected">
<label>Selected Members</label>
<table class="table table-bordered table2">
<tbody class="body2">
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Varun</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Shanu</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Salvi</td>
</tr>
<tr class="deleteRow" style="color:#f44336;cursor:pointer;">
<td>Piyush</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="table.js"></script>
</body>
</html>

Related

HTML CSS how to make a dynamic multicolumn table from a 2D table with JavaScript

I would like to make a dynamic multicolumn table from a static 2D table, like the picture below (see solution):
The correct HTML-code as folows:
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
role_arr.sort()
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>
I used jquery to iterate through the table. First created all different roles array and then individual names array. Then created individual rows for each names. I have added comments in the code.
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>

add row with specific row class

i have 2 colums and 1 add row button but i want to add row between row class "title" and "ongkir" but this my original code, but still add new row after "ongkir" pls help me
here my table
<table class="table table-hover order-list">
<tr class="title">
<th>No</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
</tr>
<tr class="ongkir">
<td>JNE</td>
</tr>
</table>
here my javascript
$(document).ready(function () {
var counter = 2;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>'+ counter + '</td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
You can use insertBefore function instead of append as follow:
$(document).ready(function () {
var counter = 2;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>'+ counter + '</td>';
newRow.append(cols);
newRow.insertBefore( "tr.ongkir" );
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover order-list">
<tr class="title">
<th>No</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
</tr>
<tr class="ongkir">
<td></td>
</tr>
</table>

javascript function in dynamically input

I'm having an issue using jQuery function multiplication (math) with dynamically created inputs (again created with jQuery). I can't get my function to bind to the new inputs. for the first row its work, but for second row it did not work (second row and more using dynamically input).
Here my html code
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem(); return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
And this my script
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
jumlah_input.setAttribute('autocomplete', 'off');
jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
function sum() {
var hrg = document.getElementById('hargaid').value;
var jml = document.getElementById('jumlahid').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('totalid').value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
Any help is appreciated.
You are not passing current id's of inputs to your sum method. and one more thing add jquery onkeyup event to your dynamic inputs. please refer below code -
$(function() {
$('#sample').on('click',additem)
$( "#nama" ).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode').val(ui.item.kode);
$('#harga').val(ui.item.harga);
}
});
});
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
var i = 1;
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
//harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
//jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
// harga_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
// jumlah_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="sample" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
Here is the sample, try this
$(function() {
$(document).on('click', '.btn-remove', function() {
// remove closest row on click of remove button
$(this).closest('tr').remove();
});
$(document).on('input', 'input.harga,input.jumlah', function() {
var hrg = $(this).closest("tr").find('input.harga').val();
var jml = $(this).closest("tr").find('input.jumlah').val();
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
$(this).closest("tr").find('input.total').val(result);
}
})
});
function additem() {
var rowHtml = '<tr>' +
'<td><input name="nama_input[]" class="nama form-control" /></td>' +
'<td><input readonly name="kode_input[]" class="kode form-control" /></td>' +
'<td><input name="harga_input[]" class="harga form-control" /></td>' +
'<td><input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" /></td>' +
'<td><input name="total_input[]" class="total form-control" /></td>' +
'<td><button class="btn btn-small btn-default btn-remove"><b>Hapus</b></button></td>' +
'</tr>';
$('#itemlist').append(rowHtml);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist'>
<tr>
<td>
<input name="nama_input[]" class="nama form-control" />
</td>
<td>
<input readonly name="kode_input[]" class="kode form-control" />
</td>
<td>
<input name="harga_input[]" class="harga form-control" />
</td>
<td>
<input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" />
</td>
<td>
<input name="total_input[]" class="total form-control" />
</td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem();
return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
I hope It will help

Show static rows one by one using javascript

I have the following table
<table class="hTab">
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
I have used following jQuery code to show the rows one by one (I have declared 10 rows in the table)
var currentrow = 0;
$('#hTab #hTr').hide();
$('#hTab #tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('#hTab #hTr:eq(' + currentrow + ')').show();
});
But at the moment it's not working. If anyone can show me the error in my code, it will be very helpful
You should use class selector . instead of id selector #, e.g :
$('.hTab .hTr:eq(' + currentrow + ')').show();
So the code will be :
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
NOTE : the button shouldn't be inside tr tag because it's outside of the table, and you have to add tds inside every tr.
Hope this helps.
var currentrow=0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"><td> A </td></tr>
<tr class="hTr"><td> B </td></tr>
<tr class="hTr"><td> C </td></tr>
</table>
<input type=button value="Show 1 more" id="onemore" />
hTab and hTr is class not a id:
so use everywhere:
$('.hTab .hTr')
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab .hTr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"> <td>A<td> </tr>
<tr class="hTr"> <td>B<td> </tr>
<tr class="hTr"> <td>C<td> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
please see the fiddle link
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});

How to insert a row in an HTML table body in JavaScript

I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);

Categories