I have this dynamic table. Add more button append a new row. Row consists of number or days and date field. Means how many days added results in date.
Now in the second row, if I add a number of days; it must check the previous previous row date or number and result the date. But rowSelected.prev('tr')[0] gives me no value.
Can anybody please help me.
$(function() {
$("#add-more").click(function() {
$("#main-table").each(function() {
let 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);
}
});
});
$(document).on('change', '.total-days', function(e) {
let rowSelected = $(this).closest('tr');
const someDate = new Date();
someDate.setDate(someDate.getDate() + parseInt($(this).val()));
const newDate = someDate.toISOString().substr(0, 10);
rowSelected.find('.expected-delivery-date').val(newDate);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-sm-6 right">
<a class="inline btn btn-primary" id="add-more">Add More</a>
</div>
<table class="table table-bordered" id="main-table" border="1">
<thead>
<tr>
<th>No.</th>
<th>From</td>
<th>Expected Delivery Date</td>
</tr>
</thead>
<tbody id="rows">
<tr>
<td><input class="form-control" type="text" name="deliverableNumber[]" /></td>
<td><input class="form-control total-days" type="number" value="1" name="deliverableNumberOfDays[]" /></td>
<td>
<input class="form-control expected-delivery-date" type="date" name="deliverableExpectedDeliveryDate[]" />
</td>
<td><i class="fa-2x fa fa-trash" onclick="SomeDeleteRowFunction(this)" title="Remove row"></i></td>
</tr>
</tbody>
</table>
I have a form, there is a button (+sign)on the form which appends a row to insert the value .In my form i am able to enter the value on the first row both fields( stationerytype and stationeryqty). But once I append a new row by clicking plus button I am not able to insert any value on staionerytype field of second row while I'm able to insert the value in the stationeryqty field of second row.
My code is:
<table class="table table-bordered" id="tb" >
<tr class="tr-header">
<th class= "col-md-1" align="centre">Sl.No.</th>
<th class= "col-md-6" align="centre">STATIONARY TYPE</th>
<th class= "col-md-4" align="centre">STATIONARY QUANTITY</th>
<th class= "col-md-1"><span class="glyphicon glyphicon-plus"></span></th>
</tr>
<tr>
<?php
for($i=1;$i<=1;$i++)
{
?>
<td><input type="text" style="text-decoration: none" name="slno" value= "<?php echo $i; ?>" ></td>
<td><select id="stationerytype" name="stationerytype[]" autocomplete="off">
<option >Stationery Name</option>
<?php $sql = "SELECT stationerytype from tblstationerytype order by stationerytype ASC ";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->stationerytype);?>"><?php echo htmlentities($result->stationerytype);?></option>
<?php }} ?>
</select></td>
<td><input type="number" name="stationeryqtyrecd" id="stationeryqtyrecd" min="0"></td>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<?php }?>
</table>
<button type="submit" name="add" class="btn btn-info" align="middle" >ADD </button>
Java script code is below
<script>
var max = 4;
var count = 1;
$(function(){
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
debugger;
data.find("input")[0].value=++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
count--;
// get all the rows in table except header.
$('#tb tr:not(.tr-header)').each(function(){
$(this).find('td:first-child input').val(this.rowIndex);
})
}
});
});
</script>
</div>
I have a form with three input fields named sl no ,stationerytype and stationeryqty There is a symbol + and - to append or delete these three field on click. I am trying the sl no field to generate Sl no automatically when i click the plus symbol and if I click - it will automatically adjust the sl no. but My sl no field remains blank .my code is
<table class="table table-bordered" id="tb" >
<tr class="tr-header">
<th class= "col-md-1" align="centre">Sl.No.</th>
<th class= "col-md-6" align="centre">STATIONARY TYPE</th>
<th class= "col-md-4" align="centre">STATIONARY QUANTITY</th>
<th class= "col-md-1"><span class="glyphicon glyphicon-plus"></span></th>
</tr>
<tr>
<?php
for($i=1;$i<=1;$i++)
{
?>
<td><input type="text" style="text-decoration: none" name="slno" value= "<?php echo $i; ?>" ></td>
<td><input type="text" style="text-decoration: none" name="stationerytype" ></td>
<td><input type="number" name="stationeryqtyrecd" id="stationeryqtyrecd" min="0"></td>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<?php }?>
</table>
<button type="submit" name="add" class="btn btn-info" align="middle" >ADD </button>
<script>
var max = 4;
var count = 1;
$(function(){
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
count++;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
});
</script>
</div>
Thanks for any suggestion :-)
in your addMore function after erasing data from the newly created row just add one more line to set the serial number in first td.
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
debugger;
data.find("input").val('');
//set the count value in first td
data.find("input")[0].value = ++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
working javascript fiddle example
I'm trying to remove row from my dynamic table. I've success to .append new row from JavaScript.
JavaScript
$(document).ready(function() {
// table #pos add-row
$(".add-row").keypress(function(e) {
if (e.which == 13) {
var barcode = $("#barcode").val();
$.ajax({
type: "post",
url: "production/ajax/load.php",
dataType: "json",
data: {
barcode: $("#barcode").val()
},
success: function(data) {
$("#pos tbody").append(data['content']);
}
});
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
alert('Success');
$("#pos tbody tr").remove();
});
})
load.php
<?php
if (isset($_POST['barcode'])) {
require '../controller/connection/connection-management.php';
$barcode = $_POST['barcode'];
$status = false;
$sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
while($row = mysqli_fetch_assoc($result)) {
$barcode = $row['code'];
$title = $row['title'];
$sellingPrice = number_format($row['selling_price'], 0, ',', '.');
$quantity = 1;
$discount = $row['discount'];
$total = number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');
$append = "<tr class='pointer'>
<td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
<td><small>{$barcode}</small></td>
<td><div style='text-align: justify'><strong>{$title}</strong></div></td>
<td align='right'>{$sellingPrice}</td>
<td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
<td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
<td align='right'>{$total}</td></td>
</tr>";
}
$status = true;
}
$data = array(
"status" => $status,
"content" => $append
);
echo json_encode($data);
}
?>
pos.php it's html table
<div class="x_title">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
</span>
<input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>Receive</li>
<li>Return</li>
<li>Purchase Order</li>
<li>Transfer</li>
<li>Store Account Payment</li>
</ul>
</div>
</div>
</div>
<div class="x_content">
<div class="table-responsive">
<table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
<th style="text-align:right" class="column-title col-sm-1">Cost </th>
<th style="text-align:center" class="column-title col-sm-2">Qty. </th>
<th style="text-align:center" class="column-title col-sm-1">Disc % </th>
<th class="column-title col-sm-1" style="text-align:right">Total </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
So when I add new row in the table, everything works fine like this picture:
But when I click trash icon with class='delete-row', that's is not working. So I think, when I append data to table tbody it's not read class or id from the new row.
Please someone help. I can't find any similar questions like mine. I just want to know, how to remove table row when I click trash icon from JavaScript.
You have two issues here (which is why I have not voted to close as a duplicate). Firstly you need to use a delegated event handler on the .delete-row element as it is appended to the DOM after load. Your current code does nothing as you attempt to attach the event handler before the element exists.
Secondly, you need to use DOM traversal to remove only the parent tr of the clicked button. At the moment your code would remove all rows. Try this:
$('#pos').on('click', '.delete-row', function() {
$(this).closest('tr').remove();
});
Did you tried delegate?
$(document).delegate('.delete-row', 'click', function(){
//your remove code here
});
You can also use on (for jquery versions 1.7.1+)
$(document).on('click', '.delete-row', function(){
//your remove code here
});
I'm trying to check my table data for empty field. I used $('td:has(input)') because all of my cell has <input type="text" class="form-control">. What I want to do if the user hit the Save button it will checked if all the textfield is empty otherwise it will prompt a message. But the user can fill one of the textfields but cannot be left blank. How can I achieve this?
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-primary" id = "save">Save</button>
</div>
Script:
<script>
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
if ($('#customFields tbody tr').length== 1)
{
alert('Cannot be left blank');
}
else
{
$('#customFields tr:last').remove();
}
});
$("#save").click(function ())
{
if ($('td:has(input)').text(function ()
{
}));
});
});
</script>
You could loop through all elements with the form-control class and make sure their combined values length is greater than zero.
$("#save").click(function (){
var values = "";
$.each($(".form-control"), function(i, c){
values = values + $(c).val().trim(); // .trim() to remove white-space
});
if(values.length > 0)
{
//Success!
}
else
{
// Error!
}
});