Delete last row of table unless its the only row with jquery - javascript

I have buttons that add and (supposedly) remove rows and elements in a table dynamically.
I cannot however get the last row in the table to delete unless it is the last remaining row.
My goal is there must be at least 1 (the first row with inputs) that cannot be deleted.
my HTML:
<TABLE id="tblTradesman">
<TR>
<TH>Name:</TH>
<TH>Arrive: (hh:mm)</TH>
<TH>Leave: (hh:mm)</TH>
</TR>
<TR>
<div id="rows">
<TD><input type="text" id="txtTradesman<? $i ?>"></TD>
<TD><input type="text" id="txtTimeArrive<? $i ?>"></TD>
<TD><input type="text" id="txtTimeLeave<? $i ?>"></TD>
</div>
</TR>
</TABLE>
<input id="btnAddTradesperson" type="button" value="Add" /><input id="btnDelTradesperson" type="button" value="Del" />
My Scripts:
$("#btnAddTradesperson").click(function () {
$("#tblTradesman").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$("#btnDelTradesperson").click(function (){
$("#tblTradesman").each(function(){
if($('tbody', this).length > 1){
$('tbody tr:last', this).remove();
}else {
alert("Must be at least 1 Trades person assigned to this job.")
}
});
});
Link to FIDDLE demo
I FIGURE IT OUT:
if($('tbody tr', this).length > 1)
Adding the 'tr' was key to it all.

Your html is invalid(div cannot be a child of tr) and need to use thead and tbody to separate the table header and body
<TABLE id="tblTradesman">
<thead>
<TR>
<TH>Name:</TH>
<TH>Arrive: (hh:mm)</TH>
<TH>Leave: (hh:mm)</TH>
</TR>
</thead>
<tbody>
<TR>
<TD><input type="text" id="txtTradesman<? $i ?>"/></TD>
<TD><input type="text" id="txtTimeArrive<? $i ?>"/></TD>
<TD><input type="text" id="txtTimeLeave<? $i ?>"/></TD>
</TR>
</tbody>
</TABLE>
<input id="btnAddTradesperson" type="button" value="Add" /><input id="btnDelTradesperson" type="button" value="Del" />
then
var $tbody = $("#tblTradesman tbody")
$("#btnDelTradesperson").click(function (){
var $last = $tbody.find('tr:last');
if($last.is(':first-child')){
alert('last is the only one')
}else {
$last.remove()
}
});
Demo: Fiddle

Your code is modified to make it work:
$("#btnAddTradesperson").click(function () {
$("#tblTradesman").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$("#btnDelTradesperson").click(function (){
$("#tblTradesman").each(function(){
if($('tbody', this).length > 0 && $('tbody tr').length > 2){
$('tbody tr:last', this).remove();
}else {
alert("Must be at least 1 Trades person assigned to this job.")
}
});
});

Related

Dynamic row numbering using javascript

I am trying to give a dynamic row number while clicking add and delete button, but in between I delete any row it is not giving proper row_number.
My td in table(dataTable) is:
echo "<td> 1 <input type='hidden' name='task_number[]' value='1'> </td>";
ADD and delete btn :
echo "<input type='button' value='Add Task' onClick=addRow('dataTable') /> ";
echo "<INPUT type='button' value='Delete Task' onclick=deleteRow('dataTable') />";
in javascript:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length -1;
var inps = document.getElementsByName('task_number[]');
var inp=inps[rowCount-1].value; // array start from 0
inp = ++inp;
var cell2 = row.insertCell(1);
cell2.innerHTML = inp;
}
Output
use this function
function setRowNumber()
{
$('#tablename tbody tr').each(function (idx) {
$(this).children("td:eq(1)").html(idx + 1);
});
}
I also put a dynamic table code. If the checkbox is checked, that row can be deleted.
orderTable();
function addRow()
{
var rowCount = $('#example tr').length;
if(rowCount == 1)
{
var tr = "<tbody><tr id='tr'><td><input type='checkbox' id='chk' name='chk' value='chk'></td>" + "<td></td><td>Task Designer</td></tr></tbody>";
$('#example thead:last').after(tr);
}
else
{
var tr = "<tr id='tr'><td><input type='checkbox' id='chk' name='chk' value='chk'></td>" + "<td></td><td>Task Designer</td></tr>";
$('#example tr:last').after(tr);
}
orderTable();
}
function deleteRow()
{
var i = 0;
$('#example input[type=checkbox]').each(function(){
if($(this).is(":checked"))
{
$('#tr' + (i + 1)).remove();
}
i = i + 1;
});
$('#example input[type=checkbox]').each(function(){
$(this).prop('checked', false);
});
orderTable();
}
function orderTable()
{
var rowCount = $('#example tbody tr').length;
if(rowCount > 0)
{
$('#example tbody tr').each(function (idx) {
var num = idx + 1;
$(this).children("td:eq(1)").html(num);
$(this).children("td:eq(2)").html('Task Designer' + num);
$(this).attr('id','tr' + num);
//set input names
$(this).children("td:eq(0)").children().attr('id','chk' + num);
$(this).children("td:eq(0)").children().attr('name','chk' + num);
$(this).children("td:eq(0)").children().attr('value','chk' + num);
});
}
}
#example
{
border:1px solid #ddd;
border-collapse: collapse;
}
th
{
background:#333;
color:white;
font-weight:bold;
height:40px;
}
td
{
text-align: center;
vertical-align: middle;
border:1px solid #ddd;
height:40px;
}
<input type='button' id="btnAdd" value='Add Task' onclick="addRow()" />
<input type='button' id="btnRemove" value='Delete Task' onclick="deleteRow()" />
<table id="example" class="display" cellspacing="0" width="100%" border="0">
<thead>
<tr>
<th>Select</th>
<th>Task Number</th>
<th>Task Description</th>
</tr>
</thead>
<tbody>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>11</td>
<td>Task Designer</td>
</tr>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>2</td>
<td>Task Designer</td>
</tr>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>3</td>
<td>Task Designer</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Change table row ID dynamically when delete in jquery

html
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center">
+
</th>
</tr>
</thead>
<tbody class="text-center">
<tr class="cb" id="row_0">
<td width="20%">
<select class="form-control select2 firstname v1" id="name1_0" name="name[]" style="width: 100%;">
<option id="1">tan</option><option id="2">lim</option>
</select></td>
<td width="20%"><input type="number" name="winlose[]" id="amt1_0" class="form-control first"></td>
<td width="20%">-</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
Jquery
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});
https://jsfiddle.net/u3hmfc7x/1/
This will dynamically add table rows or delete the row when I click the button. After that, if user deleting the second row, then the row id 2 has been deleted and row id should be interchanged dynamically. Does anyone know how to fix this :(?
For example
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>b</td></tr>
<tr class="cb" id="row_2"><td>c</td></tr>
If user delete the second, the rest will auto sequence back the ID, it will become as below
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>c</td></tr>
you don't need the id to get values from input elements, we can easily get value of each input dynamically, check below code.
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($(item).find('input[type=number]').val());
});
});
https://jsfiddle.net/n7dzhwk4/
I think a wiser option, instead of changing the ID, would be to swap the values. You can do that by changing your onclick for delete operation to:
$('tbody').on('click', '.remove', function(){
elements = $(".cb");
current = parseInt($(this).id);
for (let itr = current; itr < elements.length - 1; itr++) {
elements[itr].value = elements[itr + 1].value;
}
elements[elements.length - 1].remove();
i--;
});
Here's the code for that: https://jsfiddle.net/ckpLqs4g/
try this,
actually this is not the best method to solve this, you really dont need to change the id dynamically but i hope this will help you
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
let elementCount = 0
$('tbody').append(tr);
$('tbody').children('tr').each(function () {
this.attr('id',`row_${elementCount}`);
elementCount++;
});
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});

reading dynamically added input values into an array php

Every thing is working expect that on adding the dynamic fields,the input added is not captured into the array.Only the values in the only created input are read. HTML PART
<table class="table table-bordered table-hover order-list" >
<thead>
<tr><td>Product</td><td>Price (Ksh.) </td><td>Qty</td><td> (Ksh.)</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" name="product[]" required="" /></td>
<td><input type="text" class="form-control" name="price[]" required/></td>
<td><input type="text" class="form-control" name="quantity[]" /></td>
<td><input type="text" name="linetotal[]" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Ksh.<input type="text" name="grandtotal" readonly="readonly" /><span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
THE javascript to sum up the get the sub total and grand total is as below:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td><input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="quantity' + counter + '"/></td>';
cols += '<td><input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="quantity"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="quantity"]').val();
var linetotal = +row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
the php part to read the array is
if(isset($_POST['cinvoice']) && $_SERVER["REQUEST_METHOD"] == "POST" &&is_array($_POST["product"]) && is_array($_POST["quantity"]) && is_array($_POST["price"]) && is_array($_POST["linetotal"]))
{
$recordid="";
$firstname="";
$product="";
$quantity="";
$price="";
$linetotal="";
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
foreach ($_POST["quantity"] as $key => $qty){
$quantity.=$qty. ",";
}
foreach ($_POST["price"] as $key => $prc) {
$price.=$prc. ",";
}
foreach ($_POST["linetotal"] as $key => $linetotal) {
$linetotal.=$linetotal. ",";
}
you should pass textbox name as an array:
cols += '<td><input type="text" name="product[]"/></td>';
cols += '<td><input type="text" name="price[]"/></td>';
cols += '<td><input type="text" name="quantity[]"/></td>';
cols += '<td><input type="text" name="linetotal[]" readonly="readonly"/>
Also you can use implode function in php
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
to
$product = implode(',', $_POST["product"])

Marks should not be zero in input box

I have developed a table where student has to enter subject name and marks. i have make input box only for numeric only by javascript but i am not able to do validation so that student can not enter 0 as marks.
$("#insertbotheli13").click(function () {
$("#tablebotheli13").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="tablebotheli13" class="table table-striped table-hover">
<input type="button" class="btn green" value="Add New+" id="insertbotheli13"></input>
<thead>
<tr>
<th>Subject</th>
<th> Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control subject1" name="subject1">
</td>
<td>
<input type="text" class="form-control marks1 allownumericwithoutdecimal" name="marks1">
</td>
</tr>
</tbody>
</table>
You could check the input value if it equal to zero then remove it, check the snippet below.
Also the events should be attached with the event delegation since you're adding the input's dynamically :
$("body").on("keypress keyup blur paste", ".allownumericwithoutdecimal", function(event) {
if( $(this).val() == "0"){
$(this).val( $(this).val().replace(/0/g, "") );
}
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Hope this helps.
$("#insertbotheli13").click(function() {
$("#tablebotheli13").each(function() {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function() {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$("body").on("keypress keyup blur paste", ".allownumericwithoutdecimal", function(event) {
if( $(this).val() == "0"){
$(this).val( $(this).val().replace(/0/g, "") );
}
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="tablebotheli13" class="table table-striped table-hover">
<input type="button" class="btn green" value="Add New+" id="insertbotheli13"></input>
<thead>
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control subject1" name="subject1">
</td>
<td>
<input type="text" class="form-control marks1 allownumericwithoutdecimal" name="marks1">
</td>
</tr>
</tbody>
</table>
just put a condition on keyup and remove keypress event as there is no need of now
$("#insertbotheli13").click(function () {
$("#tablebotheli13").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$(".allownumericwithoutdecimal").on("keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if(parseInt($(this).val()) <= 0) alert("Marks should be more than Zero");
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="tablebotheli13" class="table table-striped table-hover">
<input type="button" class="btn green" value="Add New+" id="insertbotheli13"></input>
<thead>
<tr>
<th>Subject</th>
<th> Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control subject1" name="subject1">
</td>
<td>
<input type="text" class="form-control marks1 allownumericwithoutdecimal" name="marks1">
</td>
</tr>
</tbody>
</table>
your javascript call a class allownumericwithoutdecimal.If u modify the class you will get the answer.
Your code was:
$(".allownumericwithoutdecimal").on("keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if(parseInt($(this).val()) <= 0) alert("Marks should be more than Zero");
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
And Replace with this code:
$(".allownumericwithoutdecimal").keypress(function(event) {
if (!event.which || (49 <= event.which && event.which <= 57) || (48 == event.which && $(this).val())) {
/* */
} else {
event.preventDefault();
}
});
It is worked for me.
NOTE:Also you should try to delete </input> closing tag from your html.
Try this:
if (Number(form.qty.value) > 0) {
// Only executes if value is a positive number.
}

Delete and Update Rows with PHP

I do not have access to my database and cannot use a SQL function so I am trying to figure out a way to delete an array from a list when the user deletes it. Here is my code.
<table id="links" width="350px" border="1">
<tr>
<td></td>
<td><b>Display</b></td>
<td><b>Link *</b></td>
<?php
if ( isset($_POST['links']) ) {
$displays = $_POST['displays'];
$links = $_POST['links'];
$domain = $_POST['domain'];
$options = get_option("autodomain_links") or array();
foreach($links as $i => $link) {
if ( empty($displays[$i]) )
$displays[$i] = "";
if (!empty($links[$i]))
{
$autodomain = array('displays' => $displays[$i], 'links' => $links[$i], 'domain' => $domain);
$options[] = $autodomain;
}
}
//$dump = array();
update_option("autodomain_links", $options);
}
$options = get_option("autodomain_links");
if ($options) {
foreach($options as $i => $option) {
echo '<tr id="id_'.$i.'">';
echo '<td><input type="button" class="delete" value="delete" onclick="deleteRow(links)"/></td>';
echo '<td>' . $option['displays'] . '</td>';
echo '<td>' . $option['links'] . ' ' . $option['domain'] . '</td>';
echo '</tr>';
}
}
?>
This is the delete row javascript I am currently using:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
This is the code which the table above receives data from... this is the form code:
<form method="post" action="" name="links">
<!-- start -->
Domain: <input type="text" id="set-domain" value=".syr.edu" name="domain"/> <br><br>
<table id="dataTable">
<tr>
<td></td>
<td><b> Display</b></td>
<td><b> Link *</b></td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox[]"/></td>
<td><input type="text" name="displays[]"></td>
<td><input type="text" name="links[]"></td>
<td><span class="domain">.syr.edu</span><br></td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox[]"/>
<td><input type="text" name="displays[]"></td>
<td><input type="text" name="links[]"></td>
<td><span class="domain">.syr.edu</span><br></td>
</tr>
</table>
<br>
<input type="button" name="addlink" value="+" onclick="addRow('dataTable')"/>
<input type="submit" name="savelink" value="Add New Link" />
</form>
</div>

Categories