Making a counter using JavaScript/JQuery clone method in an HTML table - javascript

I need to make a counter using JavaScript/JQuery with clone method in the second column like for example the first row 1 and when I click on add button it automatically display number 2. I am using clone method in JavaScript/JQuery and I don't know how to add this. This is my full code:
var cloned = $('#myTable tr:last').clone();
$(".add-row").click(function(e) {
e.preventDefault();
cloned.clone().appendTo('#myTable');
});
$('#myTable').on('click', ".delete-row", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover table-striped table-sm" id="myTable">
<thead>
<th></th>
<th>#</th>
<th>test1</th>
<th>test2</th>
<th>test3</th>
<th>test4</th>
<th>test5</th>
</thead>
<tbody>
<tr>
<td>
delete
</td>
<td>
<!-- Counter here -->
</td>
</tr>
</tbody>
</table>
add

Consider the following.
$(function() {
function cloneLastRow(table) {
var row = $("tr:last", table);
var clone = row.clone();
$("td:eq(1)", clone).html($("tbody tr", table).length + 1);
clone.appendTo($("tbody", table));
}
function renumberTable(table) {
var count = 1;
$("tbody tr", table).each(function(i, row) {
$("td:eq(1)", row).html(count++);
});
}
$(".add-row").click(function() {
cloneLastRow($("#myTable"));
});
$("#myTable tbody").on("click", ".delete-row", function() {
var row = $(this).closest("tr");
if (confirm("Are you sure you want to delete the Row?")) {
row.fadeOut("slow", function() {
row.remove();
renumberTable($("#myTable"));
});
}
})
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover table-striped table-sm" id="myTable">
<thead>
<th> </th>
<th>#</th>
<th>test1</th>
<th>test2</th>
<th>test3</th>
<th>test4</th>
<th>test5</th>
</thead>
<tbody>
<tr>
<td>
delete
</td>
<td>
1
</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
add
There is no need for a Counter when you can just request the current length of a selector. For example, you can get the length of all the Rows in the Table Body. Initially, that is 1. The next one would be 2.
Now if the table has a unique start, lets say 20, then you would want to get that String value, cast it as an Integer, and increment that value.
$("td:eq(1)", clone).html(parseInt($("td:eq(1)", row).text()) + 1);
This would result in 21.
Update
Based on your comment, when you delete a row, you want the numbers to remain continuous. This means you need to redraw all or at least all further numbers.
function renumberTable(table){
var count = 1;
$("tbody tr", table).each(function(i, row){
$("td:eq(1)", row).html(count++);
});
}
You would then run this function directly after a Row was removed.

Related

how to select id excluding certain button or class?

I have a table like this:
The first row is thead and the second row is tbody that has id="chosen".
I made a function to remove the closest tr when the X button is clicked.
And then I'm making function to do something else when I click the whole row except for the button. (Now, function alerts message for the check)
But the problem is, if I click the X button, an alert message appears.
So, I want to exclude the X button area when calling that second function.
I tried .not() but it didn't work. :(
Html code for that table:
<table class="table table-bordered table-sm table-hover">
<thead>
<tr class="thead-light border">
<th>퀘스트 이름</th>
<th>난이도</th>
<th>목표</th>
<th>추천맵</th>
<th>반납</th>
<th width="50px">삭제</th>
</tr>
</thead>
<tbody id="chosen">
</tbody>
</table>
And my script here:
<script>
$(document).ready(function($) {
$(".clickable-row").click(function() {
var cloned = $(this).clone();
cloned.append('<td align="center";><button type="button" class="delete">X</button></td>');
$(cloned).appendTo($("#chosen"));
});
$("#reset").on("click", function() {
$("#chosen").empty();
});-
$("#chosen").on("click", ".delete", function() {
$(this).closest("tr").remove();
});
$("#chosen").not(".delete").on("click", function() {
alert("Just for check")
});
});
</script>
That first function makes a row that includes the delete button and then attaches to "choose" tbody.
You can use td:not(:last-child) to exclude last td from tr where delete button is located.
Demo Code :
//not last td
$("#chosen").on("click", "tr td:not(:last-child)", function() {
alert("Just for check")
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table table-bordered table-sm table-hover">
<thead>
<tr class="thead-light border">
<th>퀘스트 이름</th>
<th>난이도</th>
<th>목표</th>
<th>추천맵</th>
<th>반납</th>
<th width="50px">삭제</th>
</tr>
</thead>
<tbody id="chosen">
<tr>
<td>name2</td>
<td>difficulty2</td>
<td>goal2</td>
<td>recommended2</td>
<td>return2</td>
<td><button type="button" class="delete">X</button></td>
</tr>
<tr>
<td>nam2</td>
<td>difficulty2</td>
<td>goal2</td>
<td>recommended2</td>
<td>return2</td>
<td><button type="button" class="delete">X</button></td>
</tr>
</tbody>
</table>

Remove empty rows and move content from table to other row

I have table:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S13</td>
</tr>
<tr>
<td></td>
<td>S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S120</td>
</tr>
</table>
I need: where empty row with product (where product's name is empty) delete this row and move service to up product row and delete current service from up product. Example:
In this table we have product 1. I need remove S11 and paste: S13 and S14 in single row.
I need this table on result:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S13, S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S120</td>
</tr>
</table>
I think, that this we can do with javascript or jquery. I try write this code:
$('table tr').each(function () {
if (!$.trim($(this).text())) $(this).remove();
});
But this only remove empty rows..
let tr
$('table tr').each(function () {
if($(this).find('td:nth-child(1)').text().length){
tr = $(this)
tr.find('td:nth-child(2)').text('')
}else{
let td = $(tr).find('td:nth-child(2)')
td.text(td.text() + ' ' + $(this).find('td:nth-child(2)').text())
$(this).remove()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S13</td>
</tr>
<tr>
<td></td>
<td>S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S120</td>
</tr>
</table>
for (var x= 0; x < $("table.table-bordered").children[0].children.length; x++) // loop through all table rows.
{
if($("table.table-bordered").children[0].children[x].children[1].outerHTML.indexOf(',') != -1) // if the second td of the table contains a comma
{
var arr = $("table.table-bordered").children[0].children[x].children[1].innerHTML.split(','); // split the array so you make as many rows as needed
for (var y = 1; y < arr.length; y++) { // loop trough the array
var row = document.createElement('tr'); // create a new row
var first = document.createElement('td');
row.append(first) // create a empty td and add it to the row
var second = document.createElement('td'); // create another td
second.append(arr[y]); // append the value (whats after the comma)
row.append(second); // add it to the row
$("table.table-bordered > tbody").append(row); // add the row to the table
}
};
}
With this i managed to add a row to the table but i didn't have time to add it in the right place but you could look into that yourself.
I hope this helps, but to be honest I think you would be better of changing it in the backend.

table row as a counter in HTML

I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>

Retrieving column values from a table by clicking row with jquery and html

I'm using html5 and jquery to set up a dynamic table, until then I can add the elements to the table without problems, but I can not retrieve the value of its columns. so I have the following questions:
How can I recover the table data by clicking the ROW?
Should I always use the data-name, id for example as in the first
line ?
$(document).on("change", "#TabClientesAdicionados", function(e) {
alert('?');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
How can I recover the table data by clicking the ROW?
You can bind the click event to your TR elements and get the information.
Should I always use the data-name, id for example as in the first line?
Yes, because you don't want the parsed HTML to manipulate data. The data attributes are a better approach to keep related data (no HTML) to DOM elements.
Look at this code snippet
This approach binds the click event to TR elements
$('#TabClientesAdicionados tbody tr').click(function() {
var data = { name: '', id: '' };
$(this).children('td').each(function() {
var name = $(this).data('nome');
if (name) {
data.name = name;
}
var id = $(this).data('id');
if (id) {
data.id = id;
}
});
console.log(data);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno_1">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
I would do as the following snippet.
You need to bind the event to the row tr ant then get each of its children.
By adding a data attribute you could set a column name. This could also help if you eventually needed to extract the value of an specific cell.
Incidentally you could also add a second data attribute named like data-value or something similar- This in case you are worried that your parsed html content might cause you trouble with the values.
$(document).ready(function() {
$("#mytable").on('click', 'tr', onCellClick);
//Bind the event to the table row
function onCellClick() {
let row = $(this); //get the jquery Object for the row
let rowValues = {}; //An empty object to hold your data
let temp;
//extract the value of every cell in the row
//Doing it this way gives you flexibility on the amount of colums you have
row.find('td').each(function(item) {
temp = $(this);
rowValues[temp.data('column')] = temp.text();
//this could be changed to
//rowValues[temp.data('column')] = temp.data('value);
//if you desire to use a separate data-value property
});
console.log(rowValues);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%" id="mytable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td data-column="name" data-value="Jill">Jill</td> <!-Adding value property-->
<td data-column="lastname">Smith</td>
<td data-column="age">50</td>
</tr>
<tr>
<td data-column="name">Eve</td>
<td data-column="lastname">Jackson</td>
<td data-column="age">94</td>
</tr>
</table>

How can i get the value of the contenent of a TD in a TR in a table? [duplicate]

This question already has answers here:
Is it possible to get the value of a <td> element using onclick?
(6 answers)
Closed 6 years ago.
I want to get the value of the td I click
I have a table ,in this table I have many tr and td
I want to get the value of the td I selected
<table id="table" class="table" style="margin-right: auto; margin-left: auto" >
<thead>
<tr>
<th>Numero demande</th>
<th>Date prelevement</th>
<th>Um executante</th>
<th>Id preleveur</th>
</tr>
</thead>
<tbody>
#foreach(var dem in #Model)
{
<tr>
<td><a id="lienFicheDemande"> #dem.DPR</a></td>
<td>#dem.Dateprelevement </td>
<td>#dem.UM </td>
<td>#dem.PRELEVEUR.NOMCOMPLET </td>
<td id="iddem" hidden="hidden">#dem.DPR<</td>
</tr>
}
</tbody>
</table>
</body>
<script type="text/javascript" >
$(document).ready(function (e) {
$('#lienFicheDemande').click(function (e) {
alert($('#iddem')[0].innerHTML);
window.open("Appli/Home/FicheDemande?iddem=" + $('#iddem').value, "nom_popup", " menubar=no");
});
});
</script>
i want to pass the value of dem_dpr into the link in javascript
First of all, you cannot use IDs this way. They need to be unique per document. Use class instead of IDs. Then, you can use .closest('.iddem') to grab the element closest to the link you clicked and use .html() or .text() to grab it's value.
Example:
<table id="table" class="table" style="margin-right: auto; margin-left: auto" >
<thead>
<tr>
<th>Numero demande</th>
<th>Date prelevement</th>
<th>Um executante</th>
<th>Id preleveur</th>
</tr>
</thead>
<tbody>
#foreach(var dem in #Model)
{
<tr>
<td><a class="lienFicheDemande"> #dem.DPR</a></td>
<td>#dem.Dateprelevement </td>
<td>#dem.UM </td>
<td>#dem.PRELEVEUR.NOMCOMPLET </td>
<td class="iddem" hidden="hidden">#dem.DPR<</td>
</tr>
}
</tbody>
</table>
</body>
<script type="text/javascript" >
$(document).ready(function (e) {
$('.lienFicheDemande').click(function (e) {
alert($(this).closest('.iddem').html());
window.open("Appli/Home/FicheDemande?iddem=" + $(this).closest('.iddem').html(), "nom_popup", " menubar=no");
});
});
</script>
$(document).ready(function () {
$('td').click(function () {
window.open("Appli/Home/FicheDemande?iddem=" + $(this).text(), "nom_popup"," menubar=no");
});
});
For every TD, bind click function in each of them.
.text() function will get only the text in TD out from it.
It is best if you could put ID for the table.
So if you have added ID to the table. The solution would be like this:
$(document).ready(function () {
$('#table_id td').click(function () {
window.open("Appli/Home/FicheDemande?iddem=" + $(this).text(), "nom_popup"," menubar=no");
});
});

Categories