I am doing new reg processing with mass data through Ajax.
Laravel 5.7.28
PHP version 7.2
â– Press the + Button on the right side of the image to add items.
rows data can not be sent at some time.
after my examined,
there is no problem if the submit item is 166 or less, error message was issued when submit item is 167 or more.
I don't know what the problem is, please tell me how to solve it.
submit item is 166 or less
submit item 167 or more.
relate code
Route
Route::resource('ajax-crud', 'AjaxCrudController');
Controllers
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AjaxCrud;
use Validator;
class AjaxCrudController extends Controller
{
//skip...
/**
* Store Form view
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('ajax_create_items');
}
/**
* Ajax Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if(request()->ajax())
{
//show request input data
dd($request->input());
//create process
//skip...
}
}
//skip...
}
ajax_create_items.blade
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title">Add Items</h3></div>
<div class="panel-body">
<form name="add_item" id="add_item" class="form-inline">
{{ csrf_field() }}
<div class="form-group">
<label for="pr_form_number">PR Form Number: </label>
<input type="text" class="form-control" name="pr_number" value="" readonly required><br><br>
</div>
<div class="table-responsive">
<table class='table table-bordered table-hover' id="tab_logic">
<thead>
<tr class='info'>
<th style='width:10%;'>ITEM NO.</th>
<th style='width:10%;'>QTY</th>
<th style='width:10%;'>UNIT</th>
<th style='width:30%;'>DESCRIPTION</th>
<th style='width:10%;'>COST PER UNIT</th>
<th style='width:10%;'>COST PER ITEM</th>
<th style='width:10%;'>ACTION</th>
</tr>
</thead>
<thead>
<tr id="addr0">
<td class="custom-tbl"><input class='form-control input-sm'style='width:100%;' type="text" value="1" id="pr_item0" name="pr_item[]" readonly required></td>
<td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_qty0" oninput='multiply(0);' name="pr_qty[]"></td>
<td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_unit0" name="pr_unit[]"></td>
<td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_desc0" name="pr_desc[]"></td>
<td><input class='form-control input-sm' style='width:100%;' type="text" id="pr_cpu0" oninput='multiply(0);' name="pr_cpu[]"></td>
<td class="custom-tbl"><input class='estimated_cost form-control input-sm' id="pr_cpi0" style='width:100%;' type="text" name="pr_cpi[]" readonly></td>
<td class="custom-tbl"><button type="button" id="add" class="btn btn-info btn-sm"><span class="glyphicon glyphicon-plus"></span></button></td>
</tr>
</thead>
<tbody id="dynamic_field">
<tbody>
<tfoot>
<tr class='info'>
<td style='width:65%;text-align:right;padding:4px;' colspan='5'>GRAND TOTAL:</td>
<td style='padding:0px;'>
<input style='width:100%;' type='text' class='form-control input-sm' id='grand_total' name='grand_total' value='0' readonly required>
</td>
</tfoot>
</table>
</div>
<button type="button" id="submit" name="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var i = 1;
$('#add').click(function () {
i++;
$('#dynamic_field').append('<tr id="row' + i
+ '" class="dynamic-added"><td class="custom-tbl"><input id="pr_item' + i
+ '" class="form-control input-sm"style="width:100%;" type="text" value="' + i
+ '" name="pr_item[]" readonly required></td><td class="custom-tbl"><input id="pr_qty' + i
+ '"class="form-control input-sm" style="width:100%;" type="text" oninput="multiply(' + i
+ ');" name="pr_qty[]"></td><td class="custom-tbl"><input id="pr_unit' + i
+ '"class="form-control input-sm" style="width:100%;" type="text" name="pr_unit[]"></td><td class="custom-tbl"><input id="pr_desc' + i
+ '" class="form-control input-sm" style="width:100%;" type="text" name="pr_desc[]"></td><td class="custom-tbl"><input id="pr_cpu' + i
+ '" class="form-control input-sm" style="width:100%;" type="text" oninput="multiply(' + i
+ ');" name="pr_cpu[]"></td><td class="custom-tbl"><input id="pr_cpi' + i
+ '" class="estimated_cost form-control input-sm" style="width:100%;" type="text" name="pr_cpi[]" readonly></td><td class="custom-tbl"><button type="button" name="remove" id="' + i
+ '" class="btn btn-danger btn-sm btn_remove"><span class="glyphicon glyphicon-remove"></span></button></td></tr>');
});
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').click(function () {
$.ajax({
url: "{{route('ajax-crud.store')}}",
method: "POST",
data: $('#add_item').serialize(),
type: 'json',
});
});
});
</script>
<script type="text/javascript">
function multiply(id)
{
var total1 = parseFloat($('#pr_qty' + id).val()) * parseFloat($('#pr_cpu' + id).val());
$("input[id=pr_cpi" + id + "]").val(total1);
grandTotal();
}
function grandTotal()
{
var items = document.getElementsByClassName("estimated_cost");
var itemCount = items.length;
var total = 0;
for (var i = 0; i < itemCount; i++)
{
total = total + parseFloat(items[i].value);
}
document.getElementById('grand_total').value = total;
}
</script>
</body>
</html>
Related
I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità </th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}
My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check">   Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check">   Submit</span></button>
</form>
</div>
found this solution in this solution
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
in this link add commas to a number in jQuery
I am trying to apply it in my project. it works in one column but it doesn't work in price and sub total
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
var tot = totNumber.toFixed(2);
tot = commaSeparateNumber(totNumber);
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
subtotal += parseFloat($(this).val());
});
$('#subtotal').val(commaSeparateNumber(subtotal));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>
Thank you so much in advance!
The problem is that parseFloat fails to correctly parse the value from the total cost textbox because it contains one or more ,. You need to remove the , from the string before parsing to float. You can remove any ,'s by calling .replace(/,/g,'') on the textbox value in the calculateSubTotal function.
It seems that for some values the function commaSeparateNumber doesn't work as expected. I removed it from the snippet below and replaced it with toLocaleString() which takes parameters for locale and minimum/maximum fraction digits .toLocalString("en-US", { maximumFractionDigits: 2}). Set the locale to one you know uses , to separate thousands. If you know that won't be an issue you can pass undefined for the locale.
Your snippet has been updated below:
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
// .toLocaleString
var tot = totNumber.toLocaleString("en-US", { maximumFractionDigits: 2});
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
// replace ',' here
subtotal += parseFloat($(this).val().replace(/,/g,''));
});
// toLocaleString
$('#subtotal').val(subtotal.toLocaleString("en-US", { maximumFractionDigits: 2}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>
I have the below javascript and I cannot take the values from the textbox that code generates to the html
("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td><textarea name = "prodcut_name" type="text" value = " ' + value + '" class="form-control" /></td>' + '" /></td>'+ '<td><textarea name = "product_directions" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><button type="button" class="btn btn-danger remove">X</button></td>'
my html form that I need to take the values
<form action="{{action('ProductController#store', $id)}}" method="post">
<h5 class="text-center">Product</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>Product Name</td>
<td>Details</td>
<td>Remove</td>
</tr>
</thead>
<tbody id="TextBoxContainer" >
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"></i>+ Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
This is how you add text area using pure javascript.
let textAreaDiv = document.getElementById("textAreaDiv");
addButton.onclick = addTextArea;
function addTextArea() {
let textArea = document.createElement("TEXTAREA");
textArea.value = "Nice to see you";
textAreaDiv.appendChild(textArea);
}
<button id="addButton">
Add text Area
</button>
<div id="textAreaDiv">
</div>
body
<form action="server.php" method="post">
<div id="fields"></div>
<button id="btnAdd">Add</button>
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
(function() {
let fieldIndex = 0
$('#btnAdd').click(() => {
// Create every textarea with different name
let field = $('<textarea>', {
name: `field${fieldIndex++}`
})
$('#fields').append(field)
return false
})
})()
</script>
Get values on server side
server.php
<?php echo json_encode($_POST) ?>
I have 2 process for sending a data. 1st is from a table and 2nd is by textboxes. "table_select" is where I retrieve the data, and "attendee_table" is where I send the data temporarily before I save the process. On submit, it saves to database.
The problem is when I check for duplicate entries, it functions well. But when I delete one of the entries, it is still prompting that the entry is existed. NOTE: It is not yet saved in the database.
But when I save it to database, the removed entry is not included in the database. What does this mean?
Here is my Jquery/Javascript code:
attendees_id=0;
$(document).ready(function(){
// ADD ATTENDEES BY SEARCH
var addMem = [];
$("#add_button").click(function(){
$('#table_select input[type="checkbox"]:checked').each(function(){
var getRow = $(this).parents('tr');
var value = (getRow.find('td:eq(2)').html()); //names
var value1 = (getRow.find('td:eq(3)').html()); //specialty
var value3 = (getRow.find('td:eq(1)').html()); //prc
var index = $.inArray(value3, addMem);
if (index >= 0){
alert('exists');
$('input[type=checkbox]').prop('checked', false).uniform('refresh');
}
else {
$('#attendee_table tr:last').after('<tr><td></td><td><input type="text" class="form-control" name="prc[' + attendees_id + ']" id="prc" value="' + value3 + '" readonly></td><td><input type="text" class="form-control" value="' + value + '" id="names" name="name[' + attendees_id + ']" readonly></td><td><input type="text" class="form-control" value="' + value1 + '" id="specialties" name="specialty[' + attendees_id + ']" readonly></td><td><input type="button" class="btn btn-warning" name="delete_btn1[' + attendees_id + ']" id="delete_btn1" onclick="deleteMem(this)" value="Delete"></td></tr>');
addMem.push(value3,value,value1);
$("#mod_search").modal('hide');
attendees_id=attendees_id+1;
}
});
});
// ADD ATTENDEES BY ADD
var addNon = [];
$("#addRow").click(function (e) {
var val2 = $("#id_no").val();
var val = $("#attendee_name").val();
var val1 = $("#specialty").val();
var ind = $.inArray(val, addNon);
if (val == ""){
alert('Enter name of attendee.')
}
else if (val1 == ""){
alert('Enter specialty of attendee.')
}
else{
if (ind >= 0){
alert('exists');
$('#attendee_name').val('');
$('#specialty').val('');
}
else {
$('#attendee_table tr:last').after('<tr><td></td><td><input type="text" class="form-control" name="prc[' + attendees_id + ']" id="prc" value=""></td><td><input type="text" class="form-control" value="' + val + '" id="names" name="name['+ attendees_id +']" readonly></td><td><input type="text" class="form-control" value="' + val1 +'" id="specialties" name="specialty[' + attendees_id + ']" readonly></td><td><input type="button" class="btn btn-warning" name="delete_btn[' + attendees_id + ']" id="delete_btn" value="Delete" onclick="deleteNon(this)" ></td></tr>');
addNon.push(val,val1);
$('#attendee_name').val('');
$('#specialty').val('');
}
}
attendees_id=attendees_id+1;
});
});
//DELETE DATA FROM SEARCH
function deleteMem(t){
var row = t.parentNode.parentNode;
var yes = confirm('Are you sure?');
if (yes){
document.getElementById("attendee_table").deleteRow(row.rowIndex);
console.log(row);
}
else{
event.preventDefault();
}
}
//DELETE DATA FROM ADD
function deleteNon(t){
var row = t.parentNode.parentNode;
var yes = confirm('Are you sure?');
if (yes){
document.getElementById("attendee_table").deleteRow(row.rowIndex);
console.log(row);
}
else{
event.preventDefault();
}
}
This is my "table_select":
<table class="table table-hover table-managed" id="table_select">
<thead>
<tr>
<th>ID</th>
<th>PRC</th>
<th>Name</th>
<th>Speciality</th>
</tr>
</thead>
<tbody>
<?php
$sql_search="SELECT * FROM `personal_profile`";
$sql_run=mysql_query($sql_search);
while($m=mysql_fetch_array($sql_run))
{
?>
<tr>
<td><input type="checkbox" name="member_select[]" id="member_select" value="<?php #$m['id']; ?>"></td>
<td><?php echo #$m['prc_license_num']; ?></td>
<td id="names"><?php echo #$m['lastname'].', '.#$m['firstname'].' '.#$m['middlename'];?></td>
<td id="specialties"><?php echo #$m['speciality'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
"attendee_table":
<table class="table table-managed table-hover" id="attendee_table">
<thead>
<tr>
<th>No.</th>
<th>PRC</th>
<th>Name</th>
<th>Speciality</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sql_select="SELECT * FROM `event_attendees` WHERE `id`='".#$_REQUEST['member_select']."'";
$sql_run=mysql_query($sql_select);
while($row=mysql_fetch_array($sql_run))
{
?>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
//ADDING ATTENDEE BY TEXTBOX
<div class="row">
<div class="form-group">
<div class="col-md-2 col-md-offset-1">
<label class="control-label">Name</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" id="attendee_name" name="attendee_name" value="<?=#$_REQUEST['name']?>"/>
</div>
<div class="col-md-1">
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#mod_search" id="search_btn" name="search_btn" style="visibility:hidden;" >Search</button>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-2 col-md-offset-1">
<label class="control-label">Specialty/Profession</label>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="specialty" id="specialty" value="<?=#$_REQUEST['speciality']?>" />
</div>
<div class="col-md-1">
<button type="button" class="btn btn-info" id="addRow" name="addRow" style="visibility:hidden;">Add</button>
</div>
</div>
</div>
Where/what did I missed? Please help. Thank you.