Deleted data still prompts as existed - javascript

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.

Related

How to access parent element and then get it's value and then append to other element when adding a row?

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"> &nbsp 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"> &nbsp Submit</span></button>
</form>
</div>

all dataTable pages becomes one when being refreshed via AJAX

I was trying to implement this guide from this page: How to update an HTML table content without refreshing the page?
I somehow managed to implement it, unfortunately the Client-Side dataTable is destroyed when refreshing it.
By destroyed, all the data in the dataTable is in a single page.
This is the table.
<table id="earnings_amendment_account" class="table table-bordered" style="table-layout: fixed; display: none">
<thead>
<th></th>
<th>Account Code</th>
<th>Account Title</th>
<th>Account Type</th>
<th>Tools</th>
</thead>
<tbody id="table-body">
<?php include 'tableBody.php';?>
</tbody>
</table>
This is the tableBody.php
<?php include 'backend/conn.php'; ?>
<?php
$params=array();
$sql = "SELECT accountcode,accounttype,accounttitle,accounttype,postedby,dateposted,approvedby,dateapproved FROM earningsamendmentaccount";
$query = sqlsrv_query($conn, $sql, $params, array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($query === false ) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; }
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr data-key-1='".$row['postedby']."' data-key-2='".$row['dateposted']."' data-key-3='".$row['approvedby']."' data-key-4='".$row['dateapproved']."'>
<td class='details-control'></td>
<td>".$row['accountcode']."</td>
<td>".$row['accounttitle']."</td>
<td>".$row['accounttype']."</td>
<td>
<button class='btn btn-default btn-sm view btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-eye'></i> View</button>
<button class='btn btn-success btn-sm edit btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-edit'></i> Edit</button>
<button class='btn btn-danger btn-sm delete btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-trash'></i> Delete</button>
" ?>
<?php if (empty($row['approvedby'])) { echo " <button class='btn btn-warning btn-sm approve btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-check-square-o'></i> Approve</button> "; } ?>
<?php "
</tr>
";
}
?>
This is my jQuery/AJAX - (earnings_amendment_account.php)
function SubmitFormData() {
var add = $("#add").val();
var add_accountcode = $("#add_accountcode").val();
var accounttitle = $("#accounttitle").val();
var accounttype = $("#accounttype").val();
var postedby = $("#postedby").val();
var dateposted = $("#dateposted").val();
$.post("earnings_amendment_account_add.php",
{
add: add,
add_accountcode: add_accountcode,
accounttitle: accounttitle,
accounttype: accounttype,
postedby: postedby,
dateposted: dateposted
},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
$.get("tableBody.php", function(data) {
$("#table-body").html(data);
$("#earnings_amendment_account").DataTable().ajax.reload();
});
});
}
This is the modal being called.
<form autocomplete='off' id="myForm" class="form-horizontal" method="POST" action="earnings_amendment_account_add.php">
<!-- Table Loader -->
<div class="form-group" id="earnings_amendment_account_modalload">
<div class="col-sm-9" id= "earnings_amendment_account_modalload" style="width:100%">
</div></div>
<div class="form-group">
<label for="accounttitle" class="col-sm-3 control-label">Account Title</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="accounttitle" name="accounttitle" style="text-transform:uppercase;width:90%" required>
</div>
</div>
<div class="form-group" hidden>
<label for="postedby" class="col-sm-3 control-label">Posted By</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="postedby" name="postedby" value="<?php echo $user['firstname'].' '.$user['lastname']; ?>" required>
</div>
</div>
<div class="form-group" hidden>
<label for="dateposted" class="col-sm-3 control-label">Posted By</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="dateposted" name="dateposted" value="<?php echo gmdate('Y-m-d h:i:s'); ?>" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default info btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="button" onclick="SubmitFormData();" class="btn btn-primary btn-flat" name="add"><i class="fa fa-save"></i> Save</button>
<div id="results"></div>
</form>
This is the dataTable.
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({});
// Add event listener for opening and closing details
$('#earnings_amendment_account').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = earnings_amendment_account_table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Posted By : ' : tr.data('key-1'),
'Date Posted : ' : tr.data('key-2'),
'Approved By : ' : tr.data('key-3'),
'Date Approved : ' : tr.data('key-4')
})).show();
tr.addClass('shown');
} });
Is there a way for this to be fixed?
try use your datatable object
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({});
so on your jQuery/AJAX - (earnings_amendment_account.php) change $("#earnings_amendment_account").DataTable().ajax.reload(); to earnings_amendment_account_table.ajax.reload();

Laravel Ajax submit multiple row data

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>

Javascript add / remove textbox

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) ?>

How can I increment my <p> tag when I clicked add in my HTML table?

This is my whole code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pre-Enrollment</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/customcss.css">
</head>
<nav>
<ul class="nav nav-tabs">
<li role="presentatoion" class="active">Pre-Enrollment</li>
<li role="presentation">Students</li>
<li role="presentation">Subjects</li>
</ul>
</nav>
<br>
<body>
<div class="container">
<div class="row"> <!--RED-->
<div class="col-md-3" >
<form id="idNumber" action="FromEnrollment.php" method="POST">
<div class="input-group">
<!-- <input type="text" class="form-control" placeholder="ID NUMBER"> -->
<span class="input-group-btn">
<!--<form action="newPhp.php" method="POST">-->
<input type="text" placeholder="ID NUMBER" class="form-control" name="input">
<input type="submit" value="Enter" name"Enter" class="btn btn-default">
<!--</form>-->
<button class="btn btn-default" type="button" onclick="resetIdNumber()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-4 col-md-offset-3">
<select style="width: 120px;">
<option value="All">Overall Term</option>
<option value="First">First Term</option>
<option value="Second">Second Term</option>
<option value="Short">Short Term</option>
</select>
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button">Apply</button>
<button class="btn btn-default" type="button" onclick="myFunction()" value="reset">Reset</button>
</div>
</div>
<br>
<div class="row" >
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if( isset($_POST['input']) ){
include 'dbcon.php';
$Idnumber = ($_POST['input']);
$stmt = $pdo->query("SELECT * FROM students WHERE id_number = '$Idnumber'");
$currentTerm = $pdo->query("SELECT * FROM pre_enroll WHERE id_number = '$Idnumber'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result2 = $currentTerm->fetchAll(PDO::FETCH_ASSOC);
// $last_name = print_r($result[0]['last_name']);
// $first_name = print_r($result[0]['first_name']);
// $course = print_r($result[0]['course']);
echo "
<div class='col-md-2'>
<p>Name: ";
print_r($result[0]['last_name']);
echo " ";
print_r($result[0]['first_name']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Course and Year: ";
print_r($result[0]['course']);
echo"-";
print_r($result[0]['year']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Current term: ";
print_r($result2[0]['term']);
echo"</p>
</div>";
// <div class='col-md-4'>
// <p>Current Term: </p>
// </div>;
}
}else{
echo "
<div class='col-md-2'>
<p>Name: </p>
</div>
<div class='col-md-4'>
<p>Course and Year: </p>
</div>
<div class='col-md-4'>
<p>Current Term: </p>
</div>";
}
?>
</div>
<br>
<div class="row">
<div class="col-md-6">
<form id="Subjects" action="#">
<div class="input-group">
<input type="text" id="myInput" onkeyup="filterData()" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="resetSubjects()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-2">
<p>Total Units: <b> </b></p>
</div>
</div>
<br>
<?php
include 'dbcon.php';
$stmt = $pdo->query("SELECT subjects.coursenumber as 'Course No.', subjects.destitle as 'Descriptive Title', enr_stat.term as 'Term', subjects.units as 'Units' FROM subjects INNER JOIN enr_stat ON subjects.coursenumber = enr_stat.coursenumber");
?>
<div class="row">
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="myTable">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
<?php
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
// echo "<form action=''>";
echo "<tr>";
echo "<td>".$row['Course No.']."</td>";
echo "<td>".$row['Descriptive Title']."</td>";
echo "<td>".$row['Term']."</td>";
echo "<td>".$row['Units']."</td>";
echo "<input type='hidden' name='CourseNo' value='".$row['Course No.']."'/>";
echo "<input type='hidden' name='descrp' value='".$row['Descriptive Title']."'/>";
echo "<input type='hidden' name='term' value='".$row['Term']."'/>";
echo "<input type='hidden' name='units' value='".$row['Units']."'/>";
echo "
<td>
<button class='btn btn-default btn-sm' onclick='addDataToLocalStorage(this)'>
<span class='glyphicon glyphicon-plus' aria-hidden='true'></span>
</button>
</td>
";
echo "</tr>";
// echo "</form>";
}
?>
</table>
</div>
</div>
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="copy">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
</table>
</div>
</div>
</div>
<div class="col-md-offset-11">
<button class="btn btn-primary" type="button">Apply</button>
<br>
</div>
<script>
function resetIdNumber(){
document.getElementById("idNumber").reset();
}
function resetSubjects(){
document.getElementById("Subjects").reset();
}
function filterData() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function addDataToLocalStorage(r){
var courseNo = r.parentNode.parentNode.childNodes[0].innerText;
var descriptive = r.parentNode.parentNode.childNodes[1].innerText;
var term = r.parentNode.parentNode.childNodes[2].innerText;
var unit = r.parentNode.parentNode.childNodes[3].innerText;
var t = "<button onclick=clearData(this);deleteRow(this); class='btn btn-default btn-sm'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
// alert(courseNo + " " + descriptive + " " + unit);
var list = {
courseNumber: courseNo,
descriptiveTitle: descriptive,
term: term,
units: unit,
};
var jsonObject = JSON.stringify(list);
localStorage.setItem("list" + localStorage.length,jsonObject);
var thatTable = document.getElementById("copy");
var newRow = thatTable.insertRow(-1); //at the last position of the table
var newCell1 = newRow.insertCell(0);
newCell1.innerHTML = courseNo;
var newCell2 = newRow.insertCell(-1);
newCell2.innerHTML = descriptive;
var newCell3 = newRow.insertCell(-1);
newCell3.innerHTML = term;
var newCell4 = newRow.insertCell(-1);
newCell4.innerHTML = unit;
var newCell5 = newRow.insertCell(-1);
newCell5.innerHTML = t;
}
function clearData(r) {
var data = r.parentNode.parentNode.rowIndex;
var data_key = data - 1;
localStorage.removeItem(localStorage.key(data_key));
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("copy").deleteRow(i);
}
// function refresh(){
// if (localStorage.getItem("list0") != null) { ///if there is "student1" exist in localStorage
// for(i = 0; i <= localStorage.length; i++){
// var stores = localStorage.getItem("list" + i);
// var jsonString = JSON.parse(stores); //convert text to javascript object
// var thatTable = document.getElementById("copy");
// var newRow = thatTable.insertRow(-1); //at the last position of the table
// var newCell1 = newRow.insertCell(0);
// newCell1.innerHTML = courseNo;
// var newCell2 = newRow.insertCell(-1);
// newCell2.innerHTML = descriptive;
// var newCell3 = newRow.insertCell(-1);
// newCell3.innerHTML = term;
// var newCell4 = newRow.insertCell(-1);
// newCell4.innerHTML = unit;
// var newCell5 = newRow.insertCell(-1);
// newCell5.innerHTML = t;
// }
// }
//}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
How can I increment my <p>Total Units:<b> </b></p> whenever I clicked add button in my table. My table fetched some data in my database and when I clicked add, The data will copy in the next html table. I want every time I clicked the add button, my <p> tag will increment by how many units the subject is.
I tried using the stepUp() method in js but I dont know how to get the value of the units row in my html table. Is there any way to do it with my current codes?
You can just use a span with special ID
<p>Total Units:<b><span id="countRow"></span></b></p>
Then count your rows, and just
document.getElementById("countRow").innerHTML = count
Set any class name to the column units like this
<td class="unit" >2</td>
Each time of button click after run the each function like this
var total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
And set any class name to p tag
$('.p_tag_class').html('Total Units:' +total+'<b> </b>');
Update 1:
$(document).on('click','[type="button"]',function(){
$('table tbody').last('tr').append('<tr><td >2</td><td class="unit">8</td></tr>');
total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
$('.total').text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px">
<thead>
<tr>
<th>colum1</th>
<th >colum2</th>
</tr>
</thead>
<tbody>
<tr>
<td >1</td>
<td class="unit">6</td>
</tr>
<tr>
<td >2</td>
<td class="unit">8</td>
</tr>
</tbody>
</table>
<input type="button" value="new row" />
<p class="total" ></p>

Categories

Resources