Add/Delete Table Rows with Javascript - javascript

I am using this html to display my table. I am looping through data to show multiple rows.
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $srno=1;
for ($x=0; $x < count($quotes[0]->workOrderLineItem); $x++ ) {?>
<tr>
<td width="50%"><input type="text" name="detail[]" value="<?php echo $quotes[0]->workOrderLineItem[$x];?>" required=""</td>
<td width="10%"><input type="number" name="qty[]" value="<?php echo $quotes[0]->qty[$x];?>" required=""</td>
<td width="15%"><input type="number" name="price[]" value="<?php echo preg_replace("/[\$,]/", '', $quotes[0]->priceArray[$x]); ?>" required=""</td>
<td width="12%"><div class="inline"><input type="button" id="addButton" class="btn btn-primary btn-xs" value="Add"/></div><div class="inline"><input type="button" id="deleteButton" class="btn btn-primary btn-xs" value="Delete"/></div>
</tr>
<?php } ?>
</tbody>
</table>
I am then using this script to add and delete rows
$(function(){
$("#addButton").click(function(){
$(this).closest("tr").clone(true).appendTo("#myTable");
});
$("#deleteButton").click(function(){
var x = $('#myTable tr').length;
if(x == 2){
} else {
$(this).closest("tr").remove();
}
});
});
This works fine whenever I have a single table row, but when I have multiple rows the additional row "add" and "delete" buttons do not work. Only the first row buttons work. What is the best way to accomplish being able to delete and add rows from the additional rows?

remove the id from the td
<td width="12%"><div class="inline"><input type="button" class="addButton btn btn-primary btn-xs" value="Add"/></div><div class="inline"><input type="button" class="deleteButton btn btn-primary btn-xs" value="Delete"/></div>
And then change the click selector to $(".addButton") and $(".deleteButton") respectivel

can you give me the content of the $quotes var to reproduce your problem in my local environment ?
Thanks, this is the code you should be using, I just made some changes in the $quote var
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
<body>
<table id="myTable" class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$quotes = [];
$quotes[] = ['workOrderLineItem' => ["Color Change","Printed Wrap"], 'qty' => [3,2], 'price' => [267, 784] ];
$srno=1;
for ($x=0; $x < count($quotes[0]['workOrderLineItem']); $x++ ) {?>
<tr>
<td width="50%"><input type="text" name="detail[]" value="<?php echo $quotes[0]['workOrderLineItem'][$x];?>" required=""</td>
<td width="10%"><input type="number" name="qty[]" value="<?php echo $quotes[0]['qty'][$x];?>" required=""</td>
<td width="15%"><input type="number" name="price[]" value="<?php echo preg_replace("/[\$,]/", '', $quotes[0]['price'][$x]); ?>" required=""</td>
<td width="12%"><div class="inline"><input type="button" name="addButton" class="btn btn-primary btn-xs" value="Add"/></div><div class="inline"><input type="button" name="deleteButton" class="btn btn-primary btn-xs" value="Delete"/></div>
</tr>
<?php } ?>
</tbody>
</table>
<script type="text/javascript">
$(function(){
$("input[name='addButton']").on('click', function(){
$newElement = $(this).closest("tr").clone(true);
$("#myTable").append($newElement);
});
$("input[name='deleteButton']").click(function(){
var x = $('#myTable tr').length;
if(x == 2){
} else {
$(this).closest("tr").remove();
}
});
});
</script>
</body>
</html>

Related

How to append an empty row of same pattern as above row using jquery DataTable

I want to clone row using Data Table with empty data and increment on serial number.
This is my code.
<table id="tabledetail">
<thead>
<tr>
<th>S.#</th>
<th>Name</th>
<th>Type</th>
<th>Action <i class="btn btn-primary fa fa-plus rowAdd"></i></th>
</tr>
</thead>
<tbody>
<?php $sNo = 1; ?>
<?php
if(!empty($recordsDetail))
{
foreach($recordsDetail as $detail)
{
?>
<tr>
<td><?php echo $sNo; ?></td>
<td><input type="text" id="name" name="name[]" class="form-control"></td>
<td>
<select class="form-control" id="type" name="type[]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
<td><i class="btn btn-primary fa fa-plus rowAdd"></i></td>
</tr>
<?php $sNo++ ?>
<?php
}
}
?>
</tbody>
</table>
<script>
function addTableRow(jQtable) {
var $row = jQtable.find("tr:last"),
$clone = $row.clone().appendTo(jQtable);
$clone.find('[id]').attr('id', function(i, id) {
return 10 + +id;
});
$clone.find('label').remove();
$clone.find('input').each(function() {
})
}
$('.rowAdd').click(function() {
//addTableRow($('#tabledetail'));
var table = $('#tabledetail').DataTable({
aaSorting: []
});
table.row.add([]).draw();
});
$(function() {
$('table').on('click', 'tr a', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
});
});
</script>
using function addTableRow its working but i need it with data table
this is reference link
Adding row dynamically - append row from above
Try This
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table id="tabledetail">
<thead>
<tr>
<th>S.#</th>
<th>Name</th>
<th>Type</th>
<th>Action <i class="btn btn-primary fa fa-plus rowAdd"></i></th>
</tr>
</thead>
<tbody>
<?php $sNo = 1;
if(!empty($recordsDetail))
{
foreach($recordsDetail as $detail)
{
?>
<tr>
<td><?php echo $sNo; ?></td>
<td><input type="text" id="name" name="name[]" class="form-control"></td>
<td>
<select class="form-control" id="type" name="type[]">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</td>
</tr>
<?php $sNo++ ?>
<?php
}
}
?>
</tbody>
<tfoot>
<tr>
<td colspan="3">
<i class="btn btn-primary fa fa-plus rowAdd"></i>
</td>
</tr>
</tfoot>
</table>
<script>
$('.rowAdd').click(function() {
var trLastChild = $("table#tabledetail tbody tr:last-child" );
var cloneChild = trLastChild.clone();
var count=parseInt(trLastChild.find('td:first-child').html());
cloneChild.find("td:first-child").html(count+1);
$('table#tabledetail tbody').append(cloneChild);
});
</script>

how to hide datatable rows where code is have "." e.g 1.1, 1.2 through jquery?

I take data of two inputs to another page through ajax. I used these two values in the query and shown the result of the select query in a data table which is return back to success function and shown in the table on the main page.
After that, I want to use a condition that data with "." (accounting->subaccounts) hide unless He clicks a button.
I just need an idea to hide it I can do more. let me show you my code.
This is the button:
<input type="button" id="generate" onclick="getData();" value="Generate"
class="btn btn-block btn-primary btn-sm" />
The div where i shown the table:
<div class="col-lg-12 col-sm-12 col-xs-12 col-md-12" id="tab"></div>
the ajax function:
function getData() {
var date = $("#date").val();
var classId = $("#class").val();
$.ajax({
url: "ajax/getTrailBalanceData.php",
type: "POST",
data: {
"date": date,
"classId": classId,
},
cache: false,
async: false,
success: function (data) {
//alert(data);
$("#tab").html(data);
var row_main_code = $("#main_code").val();
if (row_main_code.indexOf(".") > -1) {
// $("#tbl_row").addClass("hide");
} else {
// $("#tbl_row").removeClass("hide");
// $("#main_code").parents("tr").hide();
// $("#tbl_row").addClass("hide");
// $("#main_code").val("hide");
}
}
});
}
The if(rowmaincode.indexof('.')>-1) condition in "success" I tried but not give desirable result I am confused I don't know why but let me show you the other page code:
<table id="trail_balance_list" class="table table-bordered table-condensed bootstrap-datatable datatable responsive">
<thead id="table_head">
<tr class="bg-success">
<th class=" text-center">Code</th>
<th class=" text-center">Account Title</th>
<th class=" text-center" >Debit</th>
<th class=" text-center" >Credit</th>
<th class=" text-center" >Action</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr id="tbl_row" class="">
<td><?php echo $row['main_code']; ?><input type="hidden" id="main_code" value="<?php echo $row['main_code']; ?>" /></td>
<td><?php echo $row['account_title']; ?></td>
<td></td>
<td></td>
<td class="text-center"><button class="btn btn-info"><i class="fa fa-arrow-down"></i></button></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th><input type="hidden" id="total_credit_input" name="total_credit" value="0" /></th>
<th><input type="hidden" id="total_debit_input" name="total_debit" value="0" /></th>
<td class="bg-warning text-center" id="total_debit">0.00</td>
<td class="bg-warning text-center" id="total_credit" >0.00</td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
$("#trail_balance_list").dataTable();
});
</script>
the result I get is like : (see image), I want to show only like 1,2,3,4
You have implement a similar idea in your code, hope you can do that. I have added a sample below.
$('body').on('click', '#act_button', function() {
$('#trail_balance_list > tbody > tr').each(function() {
if ($(this).find('td:first').text().indexOf('.') >= 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="act_button">hide decimal rows</button>
<table id="trail_balance_list" border="1">
<tbody>
<tr>
<td>1</td>
<td>222</td>
</tr>
<tr>
<td>33.3</td>
<td>444</td>
</tr>
<tr>
<td>555</td>
<td>666</td>
</tr>
<tr>
<td>77</td>
<td>666</td>
</tr>
</tbody>
</table>

trying to allow an empty row to the bottom of a input table using JavaScript

I am trying to create a form where the user can click on a button that will create a blank row at the bottom of the table. They can click this button for as many rows as they want to add. For some reason, when I click on the button I created, it goes back to my index.php page instead of just adding the row to the current page. Here is some of the code. Please let me know if there is more information that I should be adding here.
Thank you
JavaScript:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
<?php include 'connect.php'; ?>
<!DOCTYPE xhtml>
<html>
<head>
<style type="text/css"><?php //include'css\file.css';?></style>
<script type="text/javascript" src="js/new_line.js"></script>
<script type="text/javascript" src="js/menu.js"></script>
<body>
<button id="home" onclick="home_btn()">Home</button>
<title>New Estimate</title>
<h1>New Estimate</h1>
<?php
$sql = $conn->prepare('SELECT * FROM entire_info');
$sql -> execute();
$result = $sql ->get_result();
if ($result->num_rows!=0) {
$entire_info=$result->fetch_assoc();
}
else{
echo'Cannot find company information<br>';
}
?>
<form>
<table id="estimate_table">
<tr>
<td>
<?php
echo '<h1>'.$entire_info['name'].'</h1><br>'.
$entire_info['str_address'].'<br>'.
$entire_info['city'].', '.$entire_info['province'].' '.$entire_info['postal']
.'<br>Phone:'.$entire_info['phone'].'<br>Fax:'.$entire_info['fax'].'<br>'.$entire_info['email'].'<br>';
?>
<br>
</td>
<td colspan="3" style="text-align: right;"><?php echo '<h1>Estimate</h1>'; ?></td>
</tr>
<tr>
<td>
<table>
<tr>
<td style="vertical-align: top;">
For:<br>
<select name="estimate_for">
<?php
$sql = $conn->prepare('SELECT * FROM company');
$sql -> execute();
$result = $sql ->get_result();
if ($result->num_rows>0) {
while ($row=$result->fetch_assoc()) {
$company_name = $row['company'];
echo '<option value="'.$company_name.'">'.$company_name.'</option>';
}
}
else{
echo'Cannot find company information<br>';
}
?>
</select>
</td>
<td>
Job:<br> <textarea name="job_name" style="width: 200px ! important;" style="height: 30px ! important;"></textarea>
</td>
</tr>
</table>
</td>
<td colspan="3" style="text-align: right;">
Invoice#: <br>
Date: <input type="text" name="estimate_date" value="<?php echo date('M d, Y'); ?>">
</td>
</tr>
</table>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
</tr>
<tr>
<td ><textarea name="description" style="width: 400px" style="height: 100px ! important;"></textarea></td>
<td> <input type="text" name="hours"></td>
<td> <input type="text" name="rate"></td>
<td><input type="text" name="amount"></td>
<td>
<button onclick="new_line();">+</button>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>Subtotal</h3></td>
<td><input type="text" name="subtotal"></td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>GST (#87221 2410)
</h3></td>
<td><input type="text" name="gst"></td>
</tr>
<tr>
<td colspan="3" style="text-align: right;"><h3>Total</h3></td>
<td><input type="text" name="subtotal"></td>
</tr>
</table>
</form>
</head>
</body>
</html>
Your button is inside a <form> so by default it will behave like a submit button.
You have to set its type to a normal button by adding the type attribute:
<button onclick="new_line();" type="button">+</button>

Form does not submit or button submit not working

As far as I know this code must work but I when I coded it it does not work
The problem is that the form does not submit. How can I solve this ?
I don't even get the value of the checkbox when checked .
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<th>ID</th>
<th>Item Photo</th>
<th>Item Name</th>
<th>Stocks</th>
<th>Date Posted</th>
<th>Price</th>
<th>Actions</th>
</thead>
<tbody>
<form action ="<?php echo base_url()?>Shop/test" method="POST">
<?php
$x=1;
foreach($shop_items as $key)
{
?>
<tr>
<td><input class="checkbox" type="checkbox" name="cb[]" value="<?php $key->shop_item_id?>"> <?php echo $x;?> </td>
<td><center><img src="<?php echo base_url()?>uploads/items_main/<?php echo $key->shop_item_main_pic;?>" style = "width:60px;height:50px;"alt=""></center></td>
<td><?php echo mb_strimwidth($key->shop_item_name, 0, 18,"...");?></td>
<td style="width:10px;"><center><button><span class="fa fa-eye"></span></button></center></td>
<td><?php echo date('F,d,Y',strtotime($key->shop_item_date_posted))?></td>
<td><?php if(!$key->shop_item_sale){ echo number_format($key->shop_item_orig_price);}
else{ echo "<font color='red'>".number_format(intval($key->shop_item_orig_price-($key->shop_item_orig_price*($key->shop_item_sale/100))))."</font> ";}?></td>
<td>
Bid | View
</td>
</tr>
<?php
$x+=1;
}
?>
<button class='btn btn-danger btn-xs' type="submit" name="delete" value="delete"><span class="fa fa-times"></span> delete</button>
</form>
</tbody>
In the Controller, the structure is like this
if(isset($_POST['delete']))
{
if (isset($_POST["cb"])) {
// Checkbox is checked.
$cb = $_POST["cb"];
echo $cb;
}
else {
$cb = $_POST["cb"];
echo $cb;
}
}
If you emit all the PHP you are left with bad HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<th>ID</th>
</thead>
<tbody>
<form action="<?php echo base_url() ?>Shop/test" method="POST">
<tr>
<td>
<input class="checkbox" type="checkbox" name="cb[]" value="<?php $key->shop_item_id ?>"> <?php echo $x; ?>
</td>
</tr>
<button class='btn btn-danger btn-xs' type="submit" name="delete" value="delete">
<span class="fa fa-times"></span> delete
</button>
</form>
</tbody>
</table>
form shoul not be a child of tbody. Any content in a table should be inside th or td tags. You should place the form outside of the table and the button inside td tags:
<form action="<?php echo base_url() ?>Shop/test" method="POST">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<th>ID</th>
</thead>
<tbody>
<tr>
<td>
<input class="checkbox" type="checkbox" name="cb[]" value="<?php $key->shop_item_id ?>"> <?php echo $x; ?>
</td>
</tr>
<tr>
<td>
<button class='btn btn-danger btn-xs' type="submit" name="delete" value="delete">
<span class="fa fa-times"></span> delete
</button>
</td>
</tr>
</tbody>
</table>
</form>

how to add a checkbox in a datatable php

I have a table that displays the result of a query. I am using codeigniter by the way. I want to add a checkbox in every row. And everytime a checkbox is checked, I will enable the edit button and the delete button..
I made it this way but only on the first row, it enable and disable the button:
<div style="margin-top: 10px;margin-left: 10px;margin-bottom: 10px">
<a type="button" class="btn btn-default" href="<?php echo site_url('home/create')?>" ><span class=" fa fa-plus-circle"></span> Create </a>
<button type="button" id="edit" class="btn btn-default" disabled><span class=" fa fa-edit "></span> Edit</button>
<button type="button" class="btn btn-default" disabled > <span class=" fa fa-trash-o"></span> Delete</button>
</div>
<div class="table-responsive" style="margin-right: 10px;margin-left: 10px;margin-bottom: 10px">
<table class="table table-bordered table-hover table-striped" id="recorddata">
<thead class="header">
<tr class="well">
<th style="width: 1px"></th>
<th style="font-size: 14px;" >Date</th>
<th style="font-size: 14px;">Name</th>
<th style="font-size: 14px;">Status</th>
</tr>
</thead>
<tbody >
<?php if($result!=null){
foreach($result as $row){?>
<tr>
<td align="center"><input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->datee;?></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->name;?></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->status;?></td>
</tr>
<?php }
}
?>
</tbody>
</table><!-- END Table--></div>
here's my jquery:
<script>
$('#recs').click(function() {
if($('#recs').is(":checked")){
$('#edit').prop('disabled',false)
}
else{
$('#edit').prop('disabled',true)
}
});
</script>
You have to class instead of using id for the checkbox. Check if any of the checkbox is checked and enable edit, delete button.
<td align="center"><input type="checkbox" class="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
Add class in this line
<td align="center"><input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
Bind jquery on change event like
$(document).ready(function(){
$('.your_class').click(function(){
// check if checkbox is checked
var checked = false;
$(".your_class").each(function () {
if($(this).is(":checked"))
{
checked = true;
}
});
if(checked)
{
// enable buttons here
return;
}
// disable buttons here
});
});

Categories

Resources