table not appending dynamically in jQuery - javascript

I have made the function that helps me dynamically insert the new tr by just clicking one button, but when I reload the div with the help jquery and again hit the add new tr button it not appending.
I try to find the issue and I see the tr#row_{num} count is not resetting and starting from the last count.
for example -
If I appended 3 tr and reload the div and then, again when I click button for new tr adding it starting from 4 and not working/appending.
I used the table empty(); function but it also not working.
Please help me with how I fix this issue -?
$(document).on("click", "button#add_row", function() {
var table = $("#myTable");
var count_table_tbody_tr = $("#myTable tbody tr").length;
var row_id = count_table_tbody_tr + 1;
var html = '<tr id="row_' + row_id + '">';
html += '<td><input type="text" class="form-control ui-form-input firstname" autocomplete="off"></td>' + '<td> <input type="text" class="form-control ui-form-input lastname" autocomplete="off"></td><td></td></tr>';
if (count_table_tbody_tr >= 1) {
$("table#myTable tbody tr:first").before(html);
} else {
$("table#myTable tbody").html(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table class="table table-bordered" id="myTable" style="overflow-y: auto;">
<thead>
<tr>
<th style="text-align: center; vertical-align: middle;">First Name</th>
<th style="text-align: center; vertical-align: middle;">Last Name</th>
<th style="width: 5%;">
<button type="button" id="add_row" class="btn btn-default">Add ROW</button>
</th>
</tr>
</thead>
<tbody>
<tr id="row_1">
<td>
<input type="text" class="form-control ui-form-input firstname" autocomplete="off">
</td>
<td>
<input type="text" class="form-control ui-form-input lastname" autocomplete="off">
</td>
<td></td>
</tr>
</tbody>
</table>
My JsFddle for live working is here JSFIDDLE

Your code can be simplified to this
Note I moved the ID to to tbody
$(function() {
const $table = $("#myTable");
const $row = $("#row_1");
$("#add_row").on("click", function() {
$table.append(
$row
.clone()
.attr("id",`row_${$table.find("tr").length+1}`)
)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table class="table table-bordered" style="overflow-y: auto;">
<thead>
<tr>
<th style="text-align: center; vertical-align: middle;">First Name</th>
<th style="text-align: center; vertical-align: middle;">Last Name</th>
<th style="width: 5%;">
<button type="button" id="add_row" class="btn btn-default">Add ROW</button>
</th>
</tr>
</thead>
<tbody id="myTable">
<tr id="row_1">
<td>
<input type="text" class="form-control ui-form-input firstname" autocomplete="off">
</td>
<td>
<input type="text" class="form-control ui-form-input lastname" autocomplete="off">
</td>
<td></td>
</tr>
</tbody>
</table>
If the table is dynamic, you need
$(function() {
$(document).on("click","#add_row", function() {
const $table = $("#myTable");
const $row = $("#row_1");
$table.append(
$row
.clone()
.attr("id",`row_${$table.find("tr").length+1}`)
)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table class="table table-bordered" style="overflow-y: auto;">
<thead>
<tr>
<th style="text-align: center; vertical-align: middle;">First Name</th>
<th style="text-align: center; vertical-align: middle;">Last Name</th>
<th style="width: 5%;">
<button type="button" id="add_row" class="btn btn-default">Add ROW</button>
</th>
</tr>
</thead>
<tbody id="myTable">
<tr id="row_1">
<td>
<input type="text" class="form-control ui-form-input firstname" autocomplete="off">
</td>
<td>
<input type="text" class="form-control ui-form-input lastname" autocomplete="off">
</td>
<td></td>
</tr>
</tbody>
</table>

Related

I want to sum all the cells where the amount is and add them in the total field

I have a table in HTML with input fields and I am adding and deleting new rows on button clicks events, What I want every time new fields are created when I type in the price input then the value of each cell with a price is taken, and placed inside the total field.
Because I'm new to the world of JQuery, I'm having trouble getting the theme into the input fields.
// Special increase cells each time by clicking on add
$('#add').click(function() {
var size = $('#table_field tbody').children().length + 1;
var html = '<tr>' + '<td>' + size + '</td>' + '<td><input type="text" class="code" name="code"></td><td><input type="text" class=" form-control totalprice" name="pvu_price[]"></td><td><input type="button" class="btn btn-danger" name="remove" id="remove" value="delete" style="color:white;"></td></tr>';
$('#table_field').append(html);
});
$('#table_field').on('click', '#remove', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table_field" id="table_field">
<thead>
<tr class="thead-dark">
<th> #</th>
<th style="width: 150px; !important"> code</th>
<th style="width: 150px; !important"> price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" class="code" name="code">
<td>
<input type="text" value="" class="sub_code form-control totalprice" id="count" name="pvu_price[]">
</td>
<td>
<input type="button" class="btn btn-success" name="add" id="add" value="add" style="color: white">
</td>
</tr>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>

How to auto calculate the html table using jQuery?

Can someone or anybody help me on how to auto calculate total price in the table? Please see the image below:
Here's my code (I will included only the code that I used in the Image):
HTML:
<div class="col-12">
<div class="col drop">
<table name="services">
<tr name="services">
<td>
<select class="form-control serv" name="txt-service" id="txt-service"> //dynamic services (from database)
<option value="" readonly>--- Select Service ---</option>
<?php include "include/connect.php";
$sql="SELECT service_id,services,price FROM tbl_serviceoffered";
foreach ($con->query($sql) as $row){
echo "<option value=$row[service_id] data-price=$row[price] data-service=$row[services]>$row[services]</option>";
}
echo "</select>";
?>
</td>
<td><input type="hidden" style="text-align:right" class="form-control" name="service" id="showservice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="price" id="showprice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="item_total" id="item_total"></td>
<td><button class="btn btn-primary" name="add">Add</button></td>
</tr>
</table>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover table-bordered table-striped" name="transactions" id="transactions">
<thead>
<th></th>
<th style="text-align:center">Service Name</th>
<th style="text-align:center">Service Price</th>
<th style="text-align:center">Service Total</th>
</thead>
<tbody>
</tbody>
</table>
<td colspan="2" class="tr"> </td>
<div class="text-right">
<tr>
<td><b>Total</b></td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" style="text-align:right; font-weight:bold" class="form-control" name="grand_total" id="grand_total" placeholder="Total"></td>
</tr>
<tr>
<td>Cash Tendered</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="cashtendered" placeholder="Cash Tendered"></td>
</tr>
<tr>
<td>Change</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="change" placeholder="Change"></td>
</div>
</div>
</div>
<div class="text-right">
<button type="button" class="btn btn-primary btn-icon icon-right" name="btnSaveTransaction" id="btnSaveTransaction"><i class="fas fa-file-invoice"></i> Process Payment</a>
</div>
JS:
var id = 1;
/*Assigning id and class for tr and td tags for separation.*/
$("button[name=add]").click(function() {
var newid = id++;
$("table[name=transactions]").append('<tr id="'+newid+'">\n\
<td style="text-align:center;"><a class="btn btn-primary" href="javascript:void(0);" id="remove">Remove</a></td>\n\
<td width="100px" style="display:none;">' +newid+ '</td>\n\
<td style="text-align:center; display:none;" class="num'+newid+'">' + $("#txt-transact_num").val() + '</td>\n\
<td style="text-align:center; display:none;" class="date'+newid+'">' + $("#txt-transact_date").val() + '</td>\n\
<td style="text-align:center; display:none;" class="patientid'+newid+'">' + $("#txt-patient_id").val() + '</td>\n\
<td style="text-align:center;" class="serv'+newid+'">' + $("#showservice").val() + '</td>\n\
<td style="text-align:center; display:none;" class="servid'+newid+'">' + $(".serv option:selected").val() + '</td>\n\
<td style="text-align:right;" class="price'+newid+'">₱' + $("#showprice").val() + '</td>\n\
<td style="text-align:right;" name="txt" class="totalprice'+newid+'">₱' + $("#item_total").val() + '</td>');
$("#txt-service").val("");
$("#showprice").val("");
$("#item_total").val("0.00");
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("tbody").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#grand_total").val(sum.toFixed(2));
}
$("#transactions").on('click', '#remove', function() {
$(this).parent().parent().remove();
calculateSum();
});
As you can see, in the image above, when I add or pick some services that shows the total each of them, the textbox "total" fetch 0.00 only.
I'm still beginner in this programming language. I hope everyone can help me for our Capstone Project. Thank you!

How to inject a table row values into two separate tables

Currently I have a dynamic table that takes the values of queries to the database using forms (django)
When the table has been filled with information (there are 7 columns, but 5 of them are not visible despite having values), I would like to know how can I do so that when I select a row from the table or more, the values of the row are 'injected' into two other separate tables.
If only one row is selected from the first table, the values will be injected into two other tables, if two rows are selected from the first table then the values will be injected into 4 tables (2 tables for each selected row).
You can simply loop through checked checkboxes and then using .closest("tr") get reference of closest tr from that checked checkboxes then use .find("td:eq(1/*these values can change */)").text() to get td values and add these values to input boxes and append same to your tables.
Demo Code :
$(function() {
$("input.select-all").click(function() {
var checked = this.checked;
$("input.select-item").each(function(index, item) {
item.checked = checked;
});
});
//column checkbox select all or cancel
$("button#show-selected ,button#select-all").click(function() {
show_All();
});
function show_All() {
var html = "";
var html1 = "";
//loop through checked checkboxes
$("#searchVariantTable tbody input[type=checkbox]:checked").each(function(index, item) {
var selector = $(this).closest("tr") //get closest tr
//generate htmls
html1 += `<tr>
<td><input id="gene_2" type="text" class="form-control" placeholder="loremipsum" value="${selector.find('td:eq(1)').text()}" readonly/></td><td><input id="variant_2" type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(2)").text()}" readonly/></td>
</tr>`
html += `<tr>
<td><input type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(3)").text().trim()}" readonly/></td>
<td><input type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(4)").text().trim()}" readonly/></td>
<td><input type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(5)").text().trim()}" readonly/></td>
<td><input type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(6)").text().trim()}" readonly/></td>
<td><input type="text" class="form-control" placeholder="loremipsum" value="${selector.find("td:eq(7)").text().trim()}" readonly/></td>
</tr>`
});
$("#secondTable1").html(html1)
$("#secondTable2").html(html)
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<div class="container">
<div class="row" id="searchVariantTable">
<div class="col">
<table class="table table-hover mt-5">
<thead class="variants-table-thead">
<tr>
<th class="active">
<input type="checkbox" class="select-all checkbox" name="select-all" />
</th>
<th>Gene</th>
<th>Variant</th>
<th style="display: none;"></th>
<th style="display: none;"></th>
<th style="display: none;"></th>
<th style="display: none;"></th>
<th style="display: none;"></th>
</tr>
</thead>
<!--The <tr> are populated dynamically after form submit, I just added some dummy values.
BACKEND: (Python-Django) -->
<tbody class="variants-table-tbody">
<tr>
<td class="active">
<input id="selectedGene" type="checkbox" class="select-item checkbox" name="select-item" />
</td>
<td class="success">Gene1</td>
<td class="warning">Variant1</td>
<td style="display: none;"> #1 value1</td>
<td style="display: none;"> #2 value1</td>
<td style="display: none;"> #3 value1</td>
<td style="display: none;"> #4 value1</td>
<td style="display: none;"> #5 value1</td>
</tr>
<tr>
<td class="active">
<input id="selectedGene" type="checkbox" class="select-item checkbox" name="select-item" />
</td>
<td class="success">Gene2</td>
<td class="warning">Variant2</td>
<td style="display: none;"> #1 value2</td>
<td style="display: none;"> #2 value2</td>
<td style="display: none;"> #3 value2</td>
<td style="display: none;"> #4 value2</td>
<td style="display: none;"> #5 value2</td>
</tr>
</tbody>
</table>
<button id="select-all" class="btn btn-primary">Select all</button>
<button id="show-selected" class="btn btn-primary">Show selected</button>
</div>
</div>
<div class="row">
<div class="col-6">
<table class="table mt-5">
<thead class="variants-table-thead">
<tr>
<th style="text-align:center;">Gene</th>
<th style="text-align:center;">Variant</th>
</tr>
</thead>
<tbody class="variants-table-tbody" id="secondTable1">
<!--data will come here -->
</tbody>
</table>
</div>
<div class="col-6">
<div style="text-align: center;">
<h5>Genomic coordinate</h5>
</div>
<table class="table mt-4">
<thead class="variants-table-thead">
<tr>
<th style="text-align:center;">Opt #1</th>
<th style="text-align:center;">Opt #2</th>
<th style="text-align:center;">Opt #3</th>
<th style="text-align:center;">Opt #4</th>
<th style="text-align:center;">Opt #5</th>
</tr>
</thead>
<tbody class="variants-table-tbody" id="secondTable2">
<!--data will come here -->
</tbody>
</table>
</div>
</div>
</div>

Cycle among table cells, reading different data

Here my HTML table:
<table id="tableSensors" class="table table-sm header-fixed">
<thead class="thead-light">
<tr>
<th scope="col">Name</th>
<th scope="col">Min</th>
<th scope="col" width="10%">Max</th>
<th scope="col" width="10%">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
<tr>
<td>Temperature</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="21" readonly="">
</td>
</tr>
<tr>
<td>Humidity</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="65" readonly="">
</td>
</tr>
<tr>
<td>Pressure</td>
<td>980</td>
<td>1040</td>
<td>
<input class="form-control form-control-sm" type="text" value="1015" readonly="">
</td>
</tr>
</tbody>
</table>
The first row is to implement a filter, so it does not contain useful data.
The last column has an input tag, rather then a plain text.
I want to:
cycle among all rows/column
skipping the first row
pushing data into an array, keeping in mind the difference of the last column
This is the actual code:
function exportTable(id) { // id = #tableSensors
let data = [];
$(id).find('tr').not(':first').each(function() {
$(this).find('td').each(function() {
data.push($(this).text().trim());
});
});
// do something else
}
But:
it does not skip the first row
I'm not sure how to know if I'm in the last column to use .val() on the input tag
Ideally, I should check in each cell if there is an input tag to retrieve the data in the right way.
UPDATE
Second point fixed by myself:
$(id).find('tr').not(':first').each(function() {
$(this).find('td').each(function() {
if ($(this).find('input').length) data.push($(this).find('input').val().trim());
else data.push($(this).text().trim());
});
});
You need to filter within the tbody otherwise it will ignore the tr within thead since :first pseudo class selector selects the first one among the entire collection.
function exportTable(id) { // id = #tableSensors
let data = [];
$(id).find('tbody tr').not(':first').each(function() {
$(this).find('td').each(function() {
data.push($(this).text().trim());
});
});
console.log(data);
// do something else
}
function exportTable(id) { // id = #tableSensors
let data = [];
$('table tbody').find('tr').not(':first').each(function() {
$(this).find('td').each(function() {
data.push($(this).text().trim());
});
});
console.log(data);
// do something else
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableSensors" class="table table-sm header-fixed">
<thead class="thead-light">
<tr>
<th scope="col">Name</th>
<th scope="col">Min</th>
<th scope="col" width="10%">Max</th>
<th scope="col" width="10%">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
<tr>
<td>Temperature</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="21" readonly="">
</td>
</tr>
<tr>
<td>Humidity</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="65" readonly="">
</td>
</tr>
<tr>
<td>Pressure</td>
<td>980</td>
<td>1040</td>
<td>
<input class="form-control form-control-sm" type="text" value="1015" readonly="">
</td>
</tr>
</tbody>
</table>
<span onClick="exportTable();">click</span>
You can use [:first-child][2] as well which will work in both ways since it ignores both tr elements.
function exportTable(id) { // id = #tableSensors
let data = [];
$(id).find('tbody tr:not(:first-child)').each(function() {
$(this).find('td').each(function() {
data.push($(this).text().trim());
});
});
}
function exportTable(id) { // id = #tableSensors
let data = [];
$('table tbody tr:not(:first-child)').each(function() {
$(this).find('td').each(function() {
data.push($(this).text().trim());
});
});
console.log(data);
// do something else
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableSensors" class="table table-sm header-fixed">
<thead class="thead-light">
<tr>
<th scope="col">Name</th>
<th scope="col">Min</th>
<th scope="col" width="10%">Max</th>
<th scope="col" width="10%">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
<tr>
<td>Temperature</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="21" readonly="">
</td>
</tr>
<tr>
<td>Humidity</td>
<td>0</td>
<td>100</td>
<td>
<input class="form-control form-control-sm" type="text" value="65" readonly="">
</td>
</tr>
<tr>
<td>Pressure</td>
<td>980</td>
<td>1040</td>
<td>
<input class="form-control form-control-sm" type="text" value="1015" readonly="">
</td>
</tr>
</tbody>
</table>
<span onClick="exportTable();">click</span>

On click table td input append same tr every time

I have a problem in JavaScript to repeat a same tr after,when i click the td elements.
My html code bellow:
<table id="tabl2" class="table time-table table-bordered table-striped budrow">
<thead>
<tr>
<th class="cal-head">Rates</th>
<th class="cal-head">Start date</th>
<th class="cal-head">End date</th>
</tr>
</thead>
<tr>
<td>
<input type="number" readonly placeholder="Rates">
</td>
<td>
<input type="text" readonly id="start" placeholder="Start date">
</td>
<td>
<input type="text" class="datepicker" name="enddate" placeholder="End date">
</td>
</tr>
I tried with this js but failed:
$('.budrow').click(function(){
$(this).find('tr').append('<tr> <td></td> <td></td> <td></td> </tr>');
});
Please help me.
Try to use:
var $table = $('#tabl2');
$table.click(function(e){
var $tr = $(e.target).closest('tr');
if (($tr.parent().prop("tagName") != 'THEAD') && $tr.is(":last-child"))
$tr.after($tr.clone());
});
JSFiddle.
Bind the click event to the clicked element, select the current row using closest() and then append the new row using after() function:
$('.btn').on('click', function() {
var that = $(this);
var newRow = '<tr><td colspan="3">This is a new row</td></tr>';
that.closest('tr').after(newRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<button class="btn">click</button>
</td>
<td>
<button class="btn">click</button>
</td>
<td>
<button class="btn">click</button>
</td>
</tr>
</tbody>
</table>
You can clone and add the new row, also it will be better to use a add button separately
<button class="budrow">Add</button>
<table id="tabl2" class="table time-table table-bordered table-striped budrow">
<thead>
<tr>
<th class="cal-head">Rates</th>
<th class="cal-head">Start date</th>
<th class="cal-head">End date</th>
</tr>
</thead>
<tr>
<td>
<input type="number" readonly placeholder="Rates" />
</td>
<td>
<input type="text" readonly id="start" placeholder="Start date" />
</td>
<td>
<input type="text" class="datepicker" name="enddate" placeholder="End date" />
</td>
</tr>
</table>
then
jQuery(function ($) {
var $tr = $('#tabl2 tbody tr').eq(0);
$('button.budrow').click(function () {
var $clone = $tr.clone();
$('#tabl2').append($clone);
$clone.find('.datepicker').removeClass('hasDatepicker').datepicker();
});
$('.datepicker').datepicker();
});
Demo: Fiddle
$('.budrow tbody input').click(function(e){
makeClone(e);
});
function makeClone(e){
var newClone = $(e.target).closest("tr").clone();
$("#tabl2 tbody").append(newClone);
$(newClone).click(function(ev){
makeClone(ev);
})
}

Categories

Resources