auto sum and append data javascript - javascript

Now there is an input from add more button, the user writes some number and than he gets the sum, I am trying to get the sum automatically. its didnt work but I need the output print in text box.... for this code
here my javascript :
var i = $('table tr').length;
var count = $('table tr').length;
var row = i;
var a = 0;
for (a = 0; a <= i; a++) {
$(".addmore_" + a).on('click', function (a) {
return function() {
var box = $("#box_"+ a);
box.val( Number(box.val())+1 );
var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist"+ a +"[]'/></td>";
$("#keatas_" + a).append(data);
};
}
(a));
//this calculates values automatically
calculateSum();
$("#packinglist_"+a).on("keydown keyup", function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("#packinglist_"+ a).each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("input#netto_"+ a).val(sum.toFixed(2));
}
}
here my html :
if($_GET['mod'] == 'Buat Surat Jalan Keluar'){
function romanNumerals($num)
{
$n = intval($num);
$res = '';
/*** roman_numerals array ***/
$roman_numerals = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);
foreach ($roman_numerals as $roman => $number)
{
/*** divide to get matches ***/
$matches = intval($n / $number);
/*** assign the roman char * $matches ***/
$res .= str_repeat($roman, $matches);
/*** substract from the number ***/
$n = $n % $number;
}
/*** return the res ***/
return $res;
}
echo"</div>";
echo"
<link rel='stylesheet' type='text/css' href='css/jquery-ui.min.css' />
<link rel='stylesheet' type='text/css' href='css/main.css' />
";
$month = date('n');
$b=romanNumerals($month);
$years=date('Y');
echo"<div class='form-group'>";
$tanggal=date('d');
$s=mysql_query("SELECT * FROM surat_jalan WHERE identitas_surat = 1 AND bulantahun=$_POST[bulantahun] ORDER BY no_surat_jalan ASC");
while($a=mysql_fetch_array($s)){
$nomor = $a[2];
$potong = (int)substr($nomor,0,3);
$potong++;
}
$kosong= mysql_num_rows($s);
if(count($kosong) == 0){
$nomore = sprintf('%03s',1);
}
else {
$nomore = sprintf('%03s',$potong);
}
echo"
<body>
<form id='students' method='post' name='students' action='../Action/tambah.php?mod=suratkeluar&batas=$_POST[jumlahdata]' autocomplete='off'>
<div class='row '>
<div class='col-lg-4 '>
<div class='panel panel-default noborder'>
<div class='panel-body '>
<h3>No : ".$nomore."/$b/$years</h3>
<input class='form-control' type='hidden' id='nosurat' name='nosurat' value='".$nomore."/$b/$years' />
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Customer</label><select name='customer' class= 'form-control '>
";
$s=mysql_query('SELECT * FROM customer ORDER BY nama_customer ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_customer]_$ben[nama_customer]_$ben[alamat_customer]'>$ben[nama_customer]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Nomor PO</label><select name='nopo' class= 'form-control '>
<option value='0_-'> - </option>
";
$s=mysql_query('SELECT * FROM preorder WHERE pabrik = 0 and nonview = 0 GROUP BY no_po ORDER BY no_po ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_po]_$ben[no_po]'>$ben[no_po]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>No</th>
<th>Jenis Benang</th>
<th>Warna</th>
<th>Lot</th>
<th>Netto</th>
<th>Box</th>
<th>Cones</th>
<th>Keterangan</th>
</tr>";
$s=mysql_query("SELECT * FROM surat_jalan order by id_surat DESC");
$a=mysql_fetch_array($s);
for($i=1;$i<=$_POST['jumlahdata'];$i++)
{
$nomor = $a[0];
$iden = $nomor + $i;
echo" <tr>
<td><span id='snum'>$i.</span></td>
<input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' />
<input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' />
<input class='form-control' type='hidden' id='hiddenprice_$i' name='hiddenprice[]' />
<td><input class='form-control' type='text' id='jenisbenang_$i' name='jenisbenang[]' readonly/></td>
<td><input class='form-control' type='text' id='warna_$i' name='warna[]' readonly/></td>
<td><input class='form-control' type='text' id='lot_$i' name='lot[]' required/></td>
<td><input class='form-control sedang' type='text' id='netto_$i' name='netto[]' required/> </td>
<td><input class='form-control pendek' type='text' id='box_$i' name='box[]' /> </td>
<td><input class='form-control pendek' type='text' id='cones_$i' name='cones[]'/> </td>
<td><input class='form-control' type='text' id='keterangan_$i' name='keterangan[]'/>
<input class='form-control' type='hidden' id='keterangan_$i' name='identitas[]' value='$iden'/>
</td>
</tr>
<tr>
<td><a><span class='glyphicon glyphicon-plus addmore_$i' id='$i'></span></a><br>
<a><span class='glyphicon glyphicon-minus delete_$i'></a> </td>
<td colspan='10'>
<table id='keatas_$i' class='keatas'>
<tr>
</tr>
</table>
</tr>
</td>";
}
echo"
</table>
<div class='form-group'>
<button type='submit' class='btn btn-primary btn-lg btn-block' name='submit'>Tambah Data</button>
</div>
</div>
</form>
</body>
</div>
</div>
</div>
</div><!-- /container -->
}
so my code didnt work on it , but anything else working properly
any response would be appreciated

I have check your code. i have made some changes in your code. You have to use , in your jQuery code. Here is change "keydown, keyup" .
Also change in $('body').on('click', ".addmore_" + a, function (a) { in your for loop. and $('body').on("keydown, keyup", "#packinglist_"+a, function() {
This is because you are creating dynamic input
Please check this , it should work :
var i = $('table tr').length;
var count = $('table tr').length;
var row = i;
var a = 0;
for (a = 0; a <= i; a++) {
$(".addmore_" + a).on('click', function (a) {
return function() {
var box = $("#box_"+ a);
box.val( Number(box.val())+1 );
var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist"+ a +"[]'/></td>";
$("#keatas_" + a).append(data);
};
}
(a));
//this calculates values automatically
calculateSum();
$("#packinglist_"+a).on("keydown keyup", function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("#packinglist_"+ a).each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("input#netto_"+ a).val(sum.toFixed(2));
}
}
HTML code updates :
if($_GET['mod'] == 'Buat Surat Jalan Keluar'){
function romanNumerals($num)
{
$n = intval($num);
$res = '';
/*** roman_numerals array ***/
$roman_numerals = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);
foreach ($roman_numerals as $roman => $number)
{
/*** divide to get matches ***/
$matches = intval($n / $number);
/*** assign the roman char * $matches ***/
$res .= str_repeat($roman, $matches);
/*** substract from the number ***/
$n = $n % $number;
}
/*** return the res ***/
return $res;
}
echo"</div>";
echo"
<link rel='stylesheet' type='text/css' href='css/jquery-ui.min.css' />
<link rel='stylesheet' type='text/css' href='css/main.css' />
";
$month = date('n');
$b=romanNumerals($month);
$years=date('Y');
echo"<div class='form-group'>";
$tanggal=date('d');
$s=mysql_query("SELECT * FROM surat_jalan WHERE identitas_surat = 1 AND bulantahun=$_POST[bulantahun] ORDER BY no_surat_jalan ASC");
while($a=mysql_fetch_array($s)){
$nomor = $a[2];
$potong = (int)substr($nomor,0,3);
$potong++;
}
$kosong= mysql_num_rows($s);
if(count($kosong) == 0){
$nomore = sprintf('%03s',1);
}
else {
$nomore = sprintf('%03s',$potong);
}
echo"
<body>
<form id='students' method='post' name='students' action='../Action/tambah.php?mod=suratkeluar&batas=$_POST[jumlahdata]' autocomplete='off'>
<div class='row '>
<div class='col-lg-4 '>
<div class='panel panel-default noborder'>
<div class='panel-body '>
<h3>No : ".$nomore."/$b/$years</h3>
<input class='form-control' type='hidden' id='nosurat' name='nosurat' value='".$nomore."/$b/$years' />
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Customer</label><select name='customer' class= 'form-control '>
";
$s=mysql_query('SELECT * FROM customer ORDER BY nama_customer ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_customer]_$ben[nama_customer]_$ben[alamat_customer]'>$ben[nama_customer]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Nomor PO</label><select name='nopo' class= 'form-control '>
<option value='0_-'> - </option>
";
$s=mysql_query('SELECT * FROM preorder WHERE pabrik = 0 and nonview = 0 GROUP BY no_po ORDER BY no_po ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_po]_$ben[no_po]'>$ben[no_po]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>No</th>
<th>Jenis Benang</th>
<th>Warna</th>
<th>Lot</th>
<th>Netto</th>
<th>Box</th>
<th>Cones</th>
<th>Keterangan</th>
</tr>";
$s=mysql_query("SELECT * FROM surat_jalan order by id_surat DESC");
$a=mysql_fetch_array($s);
for($i=1;$i<=$_POST['jumlahdata'];$i++)
{
$nomor = $a[0];
$iden = $nomor + $i;
echo" <tr>
<td><span id='snum'>$i.</span></td>
<input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' />
<input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' />
<input class='form-control' type='hidden' id='hiddenprice_$i' name='hiddenprice[]' />
<td><input class='form-control' type='text' id='jenisbenang_$i' name='jenisbenang[]' readonly/></td>
<td><input class='form-control' type='text' id='warna_$i' name='warna[]' readonly/></td>
<td><input class='form-control' type='text' id='lot_$i' name='lot[]' required/></td>
<td><input class='form-control sedang' type='text' id='netto_$i' name='netto[]' required/> </td>
<td><input class='form-control pendek' type='text' id='box_$i' name='box[]' /> </td>
<td><input class='form-control pendek' type='text' id='cones_$i' name='cones[]'/> </td>
<td><input class='form-control' type='text' id='keterangan_$i' name='keterangan[]'/>
<input class='form-control' type='hidden' id='keterangan_$i' name='identitas[]' value='$iden'/>
</td>
</tr>
<tr>
<td><a><span class='glyphicon glyphicon-plus addmore_$i' id='$i'></span></a><br>
<a><span class='glyphicon glyphicon-minus delete_$i'></a> </td>
<td colspan='10'>
<table id='keatas_$i' class='keatas'>
<tr>
</tr>
</table>
</tr>
</td>";
}
echo"
</table>
<div class='form-group'>
<button type='submit' class='btn btn-primary btn-lg btn-block' name='submit'>Tambah Data</button>
</div>
</div>
</form>
</body>
</div>
</div>
</div>
</div><!-- /container -->";
}

Related

Multiple Inline Insert into table

I am trying to insert in other table using for invoicing
I've tried to create insert function but it is not inserting into table and every time I click the page or even the input tag its always says localhost but empty.
Here is the form:
<form class="form-vertical" name="save" id="save" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group row">
<label for="inv_date" >Date</label>
<div class="col-sm-8">
<input type="date" class="form-control" autocomplete="off" id="inv_date" name="inv_date" required>
</div>
</div>
<div class="form-group row">
<label for="inv_num" >Inv Number</label>
<div class="col-sm-8">
<input type="number" class="form-control" autocomplete="off" id="inv_num" name="inv_num" required>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="crud_table">
<tr>
<th width="30%">Item Name</th>
<th width="10%">Item Code</th>
<th width="45%">Description</th>
<th width="10%">Price</th>
<th width="5%"></th>
</tr>
<tr>
<td contenteditable="true" class="item_name"></td>
<td contenteditable="true" class="item_code"></td>
<td contenteditable="true" class="item_desc"></td>
<td contenteditable="true" class="item_price"></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
</div>
<div align="center">
<button type="submit" name="save" id="save" class="btn btn-info">Save</button>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td contenteditable='true' class='item_name'></td>";
html_code += "<td contenteditable='true' class='item_code'></td>";
html_code += "<td contenteditable='true' class='item_desc'></td>";
html_code += "<td contenteditable='true' class='item_price' ></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var item_name = [];
var item_code = [];
var item_desc = [];
var item_price = [];
$('.item_name').each(function(){
item_name.push($(this).text());
});
$('.item_code').each(function(){
item_code.push($(this).text());
});
$('.item_desc').each(function(){
item_desc.push($(this).text());
});
$('.item_price').each(function(){
item_price.push($(this).text());
});
$.ajax({
url:"insert.php",
method:"POST",
data:{item_name:item_name,item_code:item_code, item_desc:item_desc, item_price:item_price},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
for(var i=2; i<= count; i++)
{
$('tr#'+i+'').remove();
}
}
});
});
});
</script>
and here is the insert page:
<?php
session_start();
//insert.php
require_once ('connect.php');
if((!empty($_POST['inv_date'])) && (!empty($_POST['inv_num']))){
$inv_date = $_POST["inv_date"];
$inv_num = $_POST["inv_num"];
$query = '';
$query = 'INSERT INTO invtran (inv_date, inv_num) VALUES ("'.$inv_date.'", "'.$inv_num.'")';
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(isset($_POST["item_name"]))
{
$item_name = $_POST["item_name"];
$item_code = $_POST["item_code"];
$item_desc = $_POST["item_desc"];
$item_price = $_POST["item_price"];
$query = '';
for($count = 0; $count<count($item_name); $count++)
{
$item_name_clean = mysqli_real_escape_string($conn, $item_name[$count]);
$item_code_clean = mysqli_real_escape_string($conn, $item_code[$count]);
$item_desc_clean = mysqli_real_escape_string($conn, $item_desc[$count]);
$item_price_clean = mysqli_real_escape_string($conn, $item_price[$count]);
if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
{
$query .= '
INSERT INTO item(item_name, item_code, item_description, item_price)
VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($conn, $query))
{
echo 'Item Data Inserted';
}
else
{
echo 'Error';
}
}else
{
echo 'All Fields are Required';
}
}
}
?>
It must be inserted in different table to call them out in different page.
instead of if(isset($_POST['item_name']))
I tried different approach like this:
if ($result) {
$j = 0;
$count = sizeof($_POST['po_qty']); // ive use the sizeof() to get the count of the rows
// Use insert_id property
$po_trans_id = $link->insert_id;
$user = $_SESSION["username"];
for ($j = 0; $j < $count; $j++) {
$query = "INSERT INTO request_po (item_name, item_code, item_description, item_price) VALUES (
'".$item_name[$j]."',
'".$item_code[$j]."',
'".$item_description[$j]."',
'".$item_price[$j]."');

Insert from dynamic table input to mySQL

I have a dynamic table form input form which you can add/remove rows as you like. As someone who doesn't have much experience, I'm stuck on how to save those input into the mySQL database.
Here's what the input.php looks like
<form action="insert.php" method="post">
<div class="box-body no-padding">
<table class="table table-bordered">
<tr>
<th>Item</th>
<th>#</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
<tr>
<td><input type="text" id="item" name="item"></td>
<td><input type="text" id="no" name="no"disabled></td>
<td><input type="number" id="qty" name="qty"></td>
<td><input type="number" id="price" name="price"></td>
<td><input type="number" id="total" name ="total" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
</table>
</div>
<div class="box-body">
<div class="button-group">
<i class="fa fa-plus-circle"></i> Add Item
</div>
</div>
<div class="box-footer">
<div class="button-group pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
And here is the JS (jQuery) code that I use to add/remove rows
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function(){
$(document).ready(function(){
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item'></td>";
var no = "<td><input type='text' id='no' disabled></td>";
var qty = "<td><input type='number' id='qty'></td>";
var price = "<td><input type='number' id='price'></td>";
var total = "<td><input type='number' id='total' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
$(".table").on('click', '.remove-row', function(){
$(this).closest("tr").remove();
});
});
});
</script>
Here's what the page looks like:
input page
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db", $connection);
if(isset($_POST['submit'])){
$item = $_POST['item'];
$no = $_POST['no'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$query = mysql_query("insert into table(item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
?>
I know the insert.php won't work for my case because I need to input it as arrays. The thing is:
1. I don't know how to implement the front end so I won't have duplicate id/names when I click "Add Item"
2. I don't know how to insert the arrays (that I don't know to create) to the mysql.
I'd like to know how can I implement the save button in my case. Thank's for your help.
First, please research the mysql_* functions. They should no longer be used because they can lead to SQL injection security issues. Use mysqli_* instead or a DB layer like PDO.
Second, if you append "[]" to your input tag names then PHP will receive the data as arrays and you can loop through it in your insert.php.
<tr>
<td><input type="text" id="item" name="item[]"></td>
<td><input type="text" id="no" name="no[]" disabled></td>
<td><input type="number" id="qty" name="qty[]"></td>
<td><input type="number" id="price" name="price[]"></td>
<td><input type="number" id="total" name="total[]" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
And be sure your javascript code also adds the name attribute:
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item' name='item[]'></td>";
var no = "<td><input type='text' id='no' name='no[]' disabled></td>";
var qty = "<td><input type='number' id='qty' name='qty[]'></td>";
var price = "<td><input type='number' id='price' name='price[]'></td>";
var total = "<td><input type='number' id='total' name='total[]' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
Then in PHP you can have:
<?php
$connection = mysqli_connect("localhost", "root", "", "db");
if(isset($_POST['submit'])){
$rowCount = count($_POST['item']);
// Note that this assumes all the variables will correctly be submitted as arrays of the same length. For completeness and robustness you could add a !empty check for each value.
for ($i = 0; $i < $rowCount; $i++) {
$item = $_POST['item'][$i];
$no = $_POST['no'][$i];
$qty = $_POST['qty'][$i];
$price = $_POST['price'][$i];
$query = mysqli_query($connection, "insert into `table` (item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
}
?>

Dynamic Copy Contents from Textboxes

This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
JavaScript Code:
<script type="text/javascript">
var cc = 1;
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
</script>
HTML CODE:
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
onblur="copy_data(this);" style="font-family: Calibri; font-size: 15px;">
<br>
</div>
Please take a look at revised HTML and JS code. Hope it will work for you:
var cc = 1;
CalculateGrandTotal();
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control Total' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />";
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function copy_data(obj){
var current = $(obj);
var currentTr = current.closest("tr");
var currentTotalElem = currentTr.find(".Total");
currentTotalElem.val(current.val());
CalculateGrandTotal();
}
//calculate the grand total
function CalculateGrandTotal(){
var grandTotal = 0;
$(".Total").each(function(){
var currVal = $(this).val();
if(!isNaN(currVal))
{
grandTotal += parseFloat(currVal);
}
});
$("#grand_total").val(grandTotal);
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
style="font-family: Calibri; font-size: 15px;"></input>
<br>
<label class="col-sm-3 text-right ">Grand Total :</label> <div class="col-sm-3"> <td class="Arial_4C8966"><input name="grand_total" type="text" class="form-control" id="grand_total" size="10" />
</div>
Please try to use above JS and HTML code as it is. Replace your corresponding code with above one. Please note: your function setDeletedID doesn't work as provided HTML don't contain any element with an id txtDeletedIDs. Please check that again. Thanks.

php html javascript wrong result

This is my code
<html>
<head>
<title>
Aplikasi KRS
</title>
</head>
<body>
<p>IPK : 1.xx</p>
<form name="formTes" method="post">
<script>
function cekKrs()
{
var jum_sks = 0;
for(var i=0; i<7; i++)
{
if(document.formTes.elements[i].checked)
jum_sks += mataKuliah;
}
document.formTes.fieldJumlah.value = jum_sks;
if(jum_sks > 15)
{
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
}
}
function cekKirim()
{
if(document.formTes.fieldJumlah.value > 15)
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
else
window.location.href = "tesform.html";
}
</script>
<table border="2">
<tr><th>Kode</th><th>Mata Kuliah</th><th>SKS</th><th><Pilihan/th></tr>
<?php
include "koneksi.php";
$sql = "SELECT * FROM mata_kul";
$query = $con->query($sql);
while($mataKuliah = $query->fetch_array())
{
echo "<tr><td>". $mataKuliah['kodeMK'] ."</td>";
echo "<td>". $mataKuliah['namaMK'] ."</td>";
echo "<td>". $mataKuliah['sks'] ."</td>";
echo "<script>var mataKuliah= ".$mataKuliah['sks']."</script>";
echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs()'></td>";
}
?>
<tr><td colspan="2" align="right">Jumlah SKS</td>
<td colspan="2"><input size="3" value="0" name="fieldJumlah" type="text" readonly="readonly"></td></tr></table>
<br>
<input type="button" name="tombolKirim" value="Kirim" onclick="cekKirim()">
</form>
</body>
</html>
My question is
"Why when i click checklist it show the last value of sks in jumlah SKS, not the sks checked value i click ? like when i click checklist which have value of 2 in sks it should show 2 not 8 in jumlah SKS"
Here's the image
Can you tell me where did i go wrong ? I'm still new
I guess you need send the checkbox obj as param to cekKrs() , and in function cekKrs evaluates if obj is checked to + or - the obj.value from total
Try this DEMO
HTML ( draft )
<table>
<!-- while($mataKuliah = $query->fetch_array())
{ -->
<tr>
<!-- echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs(this)' value='".$mataKuliah['sks']."'></td>"; // PHP -->
<td><input type='checkbox' onclick='cekKrs(this)' value='1'>1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='2'>2</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='3'>3</td>
</tr>
<!-- } -->
</table>
<input size="3" value="0" name="fieldJumlah" id='fieldJumlah' type="text" readonly="readonly">
onclick='cekKrs(this)' sends checkbox obj , and you keep the mataKuliah's value inside the checkbox value
JS
function cekKrs(chkObj)
{
//Get current total
var jum_sks = parseInt(document.getElementById('fieldJumlah').value);
//Get checkbox value clicked
var mataKuliah = parseInt(chkObj.value);
//Evaluate check to + or -
if(!chkObj.checked)
{
mataKuliah = (mataKuliah * -1)
}
jum_sks += mataKuliah;
//Set new total
document.getElementById('fieldJumlah').value = jum_sks;
}

Delete table row with Javascript

Currently I have a table for information called episodes. The table has fields consisting of title, air date, episode number, and plot. I use javascript to clone the fields and also to delete them. My problem is the delete function deletes only the title, airdate, and episode number; however the plot box remains. The problem from what I can tell is that the plot is wrapped in a different <tr></tr> tag. How do I get the delete function to delete both sets?
Here is the table
<table id="template" style="display: none">
<tr class="line">
<td width="50%">
<label><?php _e('Episode Title'); ?></label>
<p>
<input type="text" name="episode_title[]" id="episode_title[]" value="" class="title regular-text" style="width:100%;" />
</p>
</td>
<td width"10%">
<label><?php _e('Airdate'); ?></label>
<p>
<input type="text" name="episode_airdate[]" id="episode_airdate[]" value="" class="airdate regular-text" style="width:100%" />
</p>
</td>
<td width="10%">
<label><?php _e('Season:'); ?></label>
<p>
<?php
for($i=1; $i<=50; $i++)
$season_nums[]=$i;
echo '<select name="episode_season[]" select id="episode_season[]" class="season regular-text" style="100%">';
echo '<option value="">' . __("Season" ) . '</option>';
foreach($season_nums as $season_num){
$selected = '';
echo '<option value="' . $season_num . '" ' . $selected . '>' . $season_num . '</option>';
}
echo '</select>';
?>
</p>
</td>
<td width="10%">
<label><?php _e('Episode:'); ?></label>
<p>
<input type="text" name="episode_number[]" id="episode_number[]" value="" class="number regular-text" style="width: 100%" />
</p>
</td>
<td width="10%" class="commands">
<a rel="delete" class="button">-</a> <a rel="add" class="button">+</a>
</td>
</tr>
<tr class="line2">
<td width="100%">
<label><?php _e('Plot:'); ?></label>
<textarea name="episode_plot[]" id="episode_plot[]" class="plot regular-text"value="" cols="100%" rows="10" tabindex="4" ><?php echo $_POST['episode_season'] ?></textarea>
</td>
</tr>
Here is the JavaScript
// Delete the "-" button in first row
$('#attachments tr:first-child .commands a[rel="delete"]').remove();
}
function items_add()
{
obj = $('#template tr').clone().appendTo('#attachments');
lines++;
if (arguments.length > 0) {
options = arguments[0];
$('.title', obj).val( options.title );
$('.airdate', obj).val( options.airdate );
$('.season', obj).val( options.season );
$('.number', obj).val( options.number );
$('.plot', obj).val( options.plot );
}
}
$('#attachments').delegate('.commands a', 'click', function()
{
var action = $(this).attr('rel');
var confirm_delete = true;
// Add action
if ('add' == action) {
items_add();
}
// Delete action
if ('delete' == action) {
// La TR en la tabla
var oTr = $(this).parent().parent();
var episode_name = $('.title', oTr).val();
var episode_airdate = $('.airdate', oTr).val();
var episode_season = $('.season', oTr).val();
var episode_number = $('.number', oTr).val();
var episode_plot = $('.plot', oTr).val();
if (episode_name != '' || episode_number != '' || episode_plot != '') {
if ( !confirm('Are you sure you want to delete ' + episode_name + '?') ) {
confirm_delete = false;
}
}
if (confirm_delete) {
oTr.remove();
lines--;
}
}
});
$(document).ready(function()
{
items_init();
});
})(jQuery);
Your help will be greatly appreciated
Change this line
var oTr = $(this).parent().parent();
to
var oTr = $(this).closest("tr");
Then use oTr.remove()
IDEA:
in php generate a random number like
$rand = time() * rand();
echo it on the line rows
<tr class="line" data-row="<?php echo $rand; ?>">
and
<tr class="line2" data-row="<?php echo $rand; ?>">
Using your delete function when someone clicks the link
var oTr = $(this).closest("tr");
var data-row =$(oTr).attr('data-row');
$('tr[data-row=' + data-row + ']').remove();
the idea is have a unique string to identify tr with line and line2 classes

Categories