How to call a php ajax/function on a html button click - javascript

I tried to include inside my page a script to add a dynamic row and every time I click on add, it save the data in database.
The problem is when I insert the data and click on add row, doesn't work.
How to write correctly this element?
<div class="mainTitle">Write a customer question : Intent</div>
<div class="adminformTitle">
<div class="form-group form-group-options col-md-12">
';
$content .= '
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">
' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '
</td>
<td class="col-md-2">
' . HTML::inputField('language', null, 'placeholder="Language"'). '
</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
';
the script ::
On click, it add a new row and save / delete data in function
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// call files
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
});
</script>

Related

Calculate the row date depending on previous row in the table

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>

Dynamically add row with jQuery

I have an application that integrated with barcode scanner, like this:
I have made a row dynamically with this snippet of code:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center">
Barcode: <br><input type="text" id="myHeader" value="5555">
</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
and here is the code that I wrapped with script tag:
<script >
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
} </script>
But the code above just add the row only when I clicked the Add Row button.
What I want for now is, when I scan a barcode with a barcode scanner, the row automatically added follow the scanned barcode result.
In this case it will be: "When the value on barcode on the header changed ( <h1 align="center">Barcode: 123123123</h1> , the result is same when I clicked the Add Row button.
So, please refer any approach, tutorial or example code how to do that, it would be very appreciated :)
For additional information: The purpose of this app is for cashier app on a store, like when the cashier scan a product, the result automatically appear on the app. And I developing it using Python Flask.
You have to listen to the changes made in the element. You can try with MutationObserver
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Listen to the changes in the header element and add row
var target = document.querySelector('#myHeader');
setTimeout(function() {
target.textContent = "New Barcode: XXXXXXXXX"; // change text after 2 seconds
}, 2000)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
$("#addrow").trigger("click"); // trigger the click event to add row if the header text is changed
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
// otherwise
observer.disconnect();
observer.observe(target, config);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
<h1 align="center" id="myHeader">Barcode: 123123123</h1>
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
Update: The updated question indicates that you can trigger the click event on blur event of the barcode input element:
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
var barcode = $("#myHeader").val().trim();// take the current barcode value
cols += '<td><input type="text" disabled value= '+ barcode +' class="form-control" name="name' + counter + '"/></td>';
cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
// Add new row by triggering the click event on focus out
var target = document.querySelector('#myHeader');
target.addEventListener('blur', function(){
$("#addrow").trigger("click");
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;">
Barcode: <br><input type="text" id="myHeader" value="5555">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Barcode</td>
<td>Item</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" style="text-align: left;">
<div align="right">
<p style="color: black;margin-right: 90px;">9.999.999</p>
</div>
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
$('#myTable tbody').append(newRow)
I think you have problem with your jQuery selector.
Try the code shown above - hope it works for you.

How to I prevent duplicate entry in cart? if try then want to qty++. jQuery

I made a purchase cart from supplier and select product and give qty then added into cart. but in next time the same product added into cart in a new row. i want t prevent it and want to increase the qty. Also have a problem i couldn't make the grand total of every line total.
Here is my HTML code of showing cart:
<table class="table table-bordered table-sm">
<thead>
<tr class="text-center">
<th>ID</th>
<th>Name</th>
<th>UoM</th>
<th>Unite Price</th>
<th>Qty</th>
<th>L. Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr class="text-right">
<td colspan="5" style="font-weight: bold;">Grand Total</td>
<td class="total text-right pr-5"></td>
</tr>
</tfoot>
</table>
Here is my jQuery Code:
$('#inputQty').keyup(function(event){
var id = $('#pro_select').val();
var qty = $(this).val();
if (event.keyCode === 13 ) {
$.ajax({
url: "{{url('selectProduct')}}",
method: 'POST',
dataType: 'JSON',
data: {id:id, _token: '{{csrf_token()}}'},
success: function(data){
var lineTotal = data.buy_price * qty;
$('tbody').append('<tr><td class="text-center">'+ data.id +'</td><td>'+ data.name +'</td><td class="text-center">'+ data.uom +'</td><td class="text-right pr-5 price">'+ data.buy_price +'</td><td class="text-right pr-5 qty">'+ qty +'</td><td class="text-right pr-5 lineTotal">'+ lineTotal +'</td><td class="text-center"><button class="btn btn-sm btn-danger remove"><i class="fas fa-times"></i></button></td></tr>');
}
});
}
});
You can clear the input field by using $(this).val(''); inside the if (event.keyCode === 13 ) {...} condition.
If you want to restrict the duplicate entries then set the next value in input as $(this).val(++qty)
Finally i solve this problem.
Here is my code:
<script>
$(function(){
$('#pro_select').change(function(){
var id = $(this).val();
$.ajax({
url: "{{url('selectProduct')}}",
method: 'POST',
dataType: 'JSON',
data: {id:id, _token: '{{csrf_token()}}'},
success: function(data){
var newRow = '<tr>'+
'<td class="text-center">'+
'<input type="hidden" class="id" value="'+ data.id +'"/>'+ data.id +'</td>'+
'<td>'+ data.name +'</td>'+
'<td class="text-center">'+ data.uom +'</td>'+
'<td>'+
'<input type="text" class="form-control form-control-sm price" value="'+ data.buy_price +'" readonly /></td>'+
'<td>'+
'<input type="number" id="inputQty" class="form-control form-control-sm qty"/></td>'+
'<td>'+
'<input type="text" class="form-control form-control-sm text-right lineTotal" readonly/></td>'+
'<td class="text-center">'+
'<button class="btn btn-sm btn-danger remove"><i class="fas fa-times"></i></button>'+
'</td>'+
'</tr>';
if ($("tbody [value='"+data.id+"']").length < 1){
$("tbody").prepend(newRow);
}
else {
alert("You have already added this Product. You Can not add this again. Please update this Product Quantity!");
}
$('#inputQty').focus();
}
});
});
$('table').delegate('.remove','click', function(){
$(this).parent().parent().remove();
total();
});
$('tbody').delegate('.price, .qty','keyup',function(){
var tr = $(this).parent().parent();
var price = tr.find('.price').val();
var qty = tr.find('.qty').val();
var lineTotal = (price * qty);
tr.find('.lineTotal').val(lineTotal);
total();
});
function total(){
var total = 0;
$('.lineTotal').each(function(){
var amount = $(this).val() -0;
total += amount;
});
$('.total').html(total +' /=');
}
});
</script>

add row with specific row class

i have 2 colums and 1 add row button but i want to add row between row class "title" and "ongkir" but this my original code, but still add new row after "ongkir" pls help me
here my table
<table class="table table-hover order-list">
<tr class="title">
<th>No</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
</tr>
<tr class="ongkir">
<td>JNE</td>
</tr>
</table>
here my javascript
$(document).ready(function () {
var counter = 2;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>'+ counter + '</td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
You can use insertBefore function instead of append as follow:
$(document).ready(function () {
var counter = 2;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>'+ counter + '</td>';
newRow.append(cols);
newRow.insertBefore( "tr.ongkir" );
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover order-list">
<tr class="title">
<th>No</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td><input type="button" style="width: 50px;" class="btn btn-success" id="addrow" value="+"></input></td>
</tr>
<tr class="ongkir">
<td></td>
</tr>
</table>

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"])

Categories