Save updated values to database and show them in html table - javascript

I have a table like the following:
<script>
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
var vouchertype = $('input[name="vouchertype[]"]').map(function(){return $(this).val();}).get();
var mode= $('select[name="mode[]"]').map(function(){return $(this).val();}).get();
// Then add it to the shown table
var baseurl='<?php echo base_url()."index.php/account/insert_voucher";?>';
$.ajax({
type: "POST",
url: baseurl,
data: $('#edit *').serialize() ,
cache: false,
success: function(html) {
alert(html);
}
});
$(this).val("Edit");
}
else $(this).val("Update");
});
</script>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0" class="tbl_grid" id="shown">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="22%" height="25" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin">Voucher Type</td>
<td width="37%" align="center" class="admin">Voucher Mode</td>
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id; ?></td>
<td><?php echo $eachrecord->voucher_type; ?></td>
<td><?php echo ucwords($eachrecord->voucher_mode); ?></td>
</tr>
<?php }
}
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0"
id="edit">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="27%" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin" >Voucher Type</td>
<td width="47%" align="center" class="admin" >Voucher Mode</td>
<!-- <td width="41%" align="center" class="narmal"> <strong>Actions</strong></td>-->
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id ; ?><input type="hidden" name="voucher_id[]" value="<?php echo $eachrecord->voucher_id; ?>" /></td>
<td><input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>" /></td>
<td><select name="mode[]" >
<option value="paidin" <?php if($eachrecord->voucher_mode=='paidin') { ?> selected="selected" <?php } ?>>Paid In</option>
<option value="paidout" <?php if($eachrecord->voucher_mode=='paidout') { ?> selected="selected" <?php } ?>>Paid Out</option>
</select></td>
</tr>
<?php } }
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
</td>
</tr>
<input id="update" type="submit" name="submit" value="Edit"/
In first table I am displaying values from database. But when user click on edit button below the table, Then that table values should be editable for user. I have succeeded in making editable fields but again when user click on submit then updated values are not displaying in first table. I know it's possible with jQuery or JavaScript. When I alert(newsales), the alert is undefined.

An easy way to handle this would be have two separate tables, and toggle between them when you edit a table. So for example we have a table that shows our normal data called shown and one with the input and select for a user to enter data called edit. These tables will share the same button, and when clicked it will toggle between the tables, making it look like it's switching between edit and show mode. This way we can just copy the values from the edit table to the text in the shown table. Here is an example:
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
// Get the data from the edit table
var newSales = $("#edit tr:nth-child(1) td input[name='vouchertype']").val();
var newPay = $("#edit tr:nth-child(1) td select[name='mode']").val();
var newTax = $("#edit tr:nth-child(2) td select[name='tax']").val();
// Then add it to the shown table
$("#shown tr:nth-child(1) td:nth-child(2)").text(newSales);
$("#shown tr:nth-child(1) td:nth-child(3)").text(newPay);
$("#shown tr:nth-child(2) td:nth-child(1)").text(newTax);
$(this).val("Edit");
}
else $(this).val("Update");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="shown">
<tr>
<td>Sr no</td><td>Sales</td><td>Paid in</td>
</tr>
<tr><td>Taxed</td></tr>
</table>
<table id="edit">
<tr>
<td>Sr no</td><td><input type="text" name="vouchertype" value="Sales" /></td>
<td>
<select name="mode">
<option value="paidin">Paidin</option>
<option value="paidout">Paidout</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="tax">
<option value="Taxed">Taxed</option>
<option value="Not Taxed">Not Taxed</option>
</select>
</td>
</tr>
</table>
<input id="update" type="submit" name="submit" value="Edit"/>
Notice: This is an answer to the original question, which is quite different then the new question added in as an edit.

Related

Keep Hidden Table Column/Cells Visible Using Session Storage

I have a table where I can check a checkbox and it will log all of the contents in the row. Once you check a checkbox, another column (Quantity #) appears with a textbox/spinner inside the cell. If it is unchecked, then the corresponding textbox/spinner disappears.
I want to use session storage to be able to keep any cells in the Quantity # column visible if the row is checked throughout refreshes until the page is closed. I was able to use session storage to keep the checkboxes checked, but am having a problem with getting the Quantity # column to remain visible so long as the checkbox is checked for that row.
How can I do this?
I have included the HTML for the checkbox row and the JavaScript that keeps the checkboxes checked so it can be used to base an answer off of if needed.
HTML for the checkbox and the appearing table cell:
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="quantity_num ui-widget-content" name="rows[0][0][quant]" style="display: none;"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
JavaScript for the session storage for the checkbox and for the spinner in the appearing table cell:
$(function(){
$(':checkbox').each(function() {
// Iterate over the checkboxes and set their "check" values based on the session data
var $el = $(this);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});
$('input:checkbox').on('change', function() {
// save the individual checkbox in the session inside the `change` event,
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
$(function () {
$(".check").change(function(){
$(this).closest('tr').find('td.quantity_num').toggle(this.checked);
console.log($('input.check').is(':checked'));
var quantity = $(this).closest('tr').find('td.quantity').data('quantity');
console.log(quantity);
if($('input.check').is(':checked'))
$(this).closest('table').find('th.num').toggle(true);
else
$(this).closest('table').find('th.num').toggle(false);
$(this).closest("tr").find(".spinner" ).spinner({
spin: function( event, ui ) {
if ( ui.value > quantity ) {
$( this ).spinner( "value", quantity );
return false;
} else if ( ui.value <= 1 ) {
$( this ).spinner( "value", 1 );
return false;
}
}
});
});
});
EDIT:
HTML/PHP for table:
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content"><input type="hidden"><?php echo $row['Loc'];?></td>
<td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td name="rows[0][0][sku]" class="sku ui-widget-content" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td name="rows[0][0][special-id]" class="special-id ui-widget-content" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td name="rows[0][0][description]" class="description ui-widget-content" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td name="rows[0][0][unit]" class="unit ui-widget-content" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td name="rows[0][0][quant]" style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>

Set value of HTML element from javascript

I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});

Can I able to write with out isset($post[]) for the below code

<script>
function removeAllRowsContainingCheckedCheckbox() {
alert("hello");
for (var rowi= table.rows.length; rowi-->0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;) {
//alert("inside for");
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
//alert("indide if ")
row.parentNode.removeChild(row);
break;
}
}
}
}
</script>
<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table border="1" id="table">
<tr>
<td colspan="2">Select Technolgy:</td>
</tr>
<tr>
<td>c</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>hadoop</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>core java</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>Javascript</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>springs</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit" name="sub"></td>
</tr>
<input type='button' value='del' onclick='removeAllRowsContainingCheckedCheckbox();'>Click me to delete
</table>
</form>
<?php
if(isset($_POST['sub']))
{
$db = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=ndem$123");
if(!$db){
echo "Error : Unable to open database\n";
} else {
echo "Opened database successfully\n";
}
$checkbox1=$_POST['techno'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1."";
echo '<script>alert("Inserted Successfully")</script>';
}
$in_ch=pg_query("insert into news_table(technology) values ('$chk')");
echo "the check box value is " . $in_ch;
if($in_ch==1)
{
echo '<script>alert("Inserted Successfully")</script>';
echo "Records created successfully\n";
}
else
{
echo pg_last_error($db);
}
pg_close($db);
}
?>
</body>
</html>
For the submit can i able to write javascript function with out using
$checkbox1=$_POST['techno'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1."";
echo '<script>alert("Inserted Successfully")</script>';
}
above code because if(isset($_POST['sub'])) is reloading the already submitted checkboxs in the table so user may confuse after delete the page will again show all the check box those who are submitted also .. Please suggest alternatives for this any ways i want to insert the checked checkboxes into database but my thought is to delete the checked submitted also in the table.

Submit button with 2 actions depends on dropdown menu

I am trying to figure out how to submit button with two actions based on dropdown list that I get from MySQL. One is for updating to database and then proceed to nextpage while the other actions is to proceed to specific page. I've tried all the solution but most of them only has a few dropdown menu, mine have 40 menus.
This is my JavaScript
<script type='text/javascript'>
$(window).load(function(){
//$(document).ready(function() {
<!--To Enable button "MULA"-->
$('#lst_respon').change(function() {
if ($(this).find(":selected").val()!='11') {
$('#button').attr('disabled',true);
} else {
$('#button').removeAttr('disabled');
}
});
$('#lst_respon').change(function()
{
$('#form1').submit();
});
});
function changeTextBox()
{
var val=$('#lst_respon').val();
if(val==='11')
{
$('#value').prop('disabled', true);
}
else{$('#value').removeAttr("disabled");}
}
</script>
And this is my HTML
<div align="center">
<table width="60%" border="1" class="zui-table">
<thead>
<tr>
<th colspan="3" align="center">Status</th>
</tr>
</thead>
<tr>
<?php
$smt = $conn->prepare('select * From lookup_caraterima');
$smt->execute();
$data = $smt->fetchAll();
$smt2 = $conn->prepare('select * From lookup_kodrespon');
$smt2->execute();
$data2 = $smt2->fetchAll();
?>
<td width="253">Cara Terima</td>
<td width="5">:</td>
<td width="164">
<select name="lst_cterima" id="lst_cterima">
<?php foreach ($data as $row): ?>
<option value="<? echo $row["kodterima"];?>"><? echo $row["jenis"];?>
</option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td>Kod Respon</td>
<td>:</td>
<td>
<select name="lst_respon" id="lst_respon" onchange="changeTextBox()">
<?php foreach ($data2 as $row2): ?>
<option value="<? echo $row2["kod"];?>"><? echo $row2["kod"].'- '.$row2 ["Keterangan"];?></option>
<?php endforeach ?>
</select></td>
</tr>
<tr>
<td><label for ="sebab">Sebab</label></td>
<td>:</td>
<td><input type="textbox" id="value" size="100" disabled</td>
</tr>
<tr>
<td colspan="3" align="center"><form name="form1" method="post" action="main.php?load=4&SerialID=<?php echo $noSiri; ?>&month=<?php echo $monthA;?>&year=<?php echo $yearA;?>&tab=A">
<input type="submit" name="button" id="button" value="Teruskan" class="myButton">
</form></td>
</tr>
</table>
</div>
For an automated solution to submit a form based a dropdown selection, you could try using the data attribute, something like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form id="tester">
<select name="test">
<option value="best" data-instructions='<?php echo json_encode(array('action'=>'page1')); ?>'>Best</option>
<option value="rest" data-instructions='<?php echo json_encode(array('action'=>'page2')); ?>'>Rest</option>
<option value="guest" data-instructions='<?php echo json_encode(array('action'=>'page3')); ?>'>Guest</option>
<option value="lest" data-instructions='<?php echo json_encode(array('action'=>'page4')); ?>'>Lest</option>
</select>
<input type="submit" name="submit" value="SUBMIT" />
</form>
<script>
$(document).ready(function() {
$('#tester').submit(function(e) {
// Stop form from submitting
e.preventDefault();
// Get the select dropdown
var thisSelect = $(this).find('select[name=test]');
// Get the value
var thisVal = thisSelect.val();
// Get the options separately
var thisOpts = thisSelect.children();
// Create a holder
var thisData = {};
// Loop through the options
$.each(thisOpts,function(k,v) {
// Get the current value
var currVal = $(v).attr('value');
// If the current value is the same as the value selected
if(currVal == thisVal) {
// Get the instructions from the option
thisData = $(v).data('instructions');
// Stop looping
return false
}
});
console.log(thisData);
});
});
</script>
On submission, the selection will give you an object that you can use to instruct how to submit the form:
// thisData.action
{action: "page2"}

how to print thead of the table on each print page?

my table contain large number of dynamic rows when i print or print preview it i get only table thead on only first page using window.print() function ..but i want table thead on each print page... help?
<div id="printablediv" >
<div style="padding:8px;font-size: 13px;">
<center>
<?php
$sumMul = 0;
$sumBil = 0;
?>
<?php $total = $total_ni = $total_aa = $total_pe = $total_bak = $total_cnt = 0; ?>
<table cellpadding="0" cellspacing="0" border="1" style="font-size: 13px;" >
<thead id="head">
<tr bgcolor="#333333" style="color:#black;font-weight: bold;">
<th width="100" align="center">Donor</th>
<th width="100" align="center">Loan No.</th>
<th width="120" align="center">Value Date</th>
<th width="90" align="center">Curr</th>
<th width="150" align="center">Multilateral</th>
<th width="150" align="center">Bilateral</th>
<th width="150" align="center">Forex</th>
<th width="150" align="center">Multilateral</th>
<th width="150" align="center">Bilateral</th>
</tr>
</thead>
<?php $previousValue = $list[0]->LOAN_ID; ?>
<?php $flag = 0; ?>
<?php foreach ($list as $key => $val): ?>
<tr>
<td align="center"><?php echo $val->EX_DONOR_CODE; ?></td>
<td align="center"><?php echo $val->LOAN_ID; ?></td>
<td align="center"><?php echo $val->VALUE_DATE; ?></td>
<td align="center"><?php echo $val->TRANSACTION_CURRENCY_CODE; ?></td>
<td align="right"><?php
if ($val->DONOR_TYPE == 'MULTILATERL') {
$sumMul += $val->COMMIT_CUR_AMT;
echo $val->COMMIT_CUR_AMT;
}
?></td>
<td align="right"><?php
if ($val->DONOR_TYPE == 'BILATERAL') {
$sumBil += $val->COMMIT_CUR_AMT;
echo $val->COMMIT_CUR_AMT;
}
?></td>
<td align="right"><?php //reports::report1_5Forex($val->TRANSACTION_CURRENCY_CODE ,$val->VALUE_DATE) ?></td>
<td align ="right"></td>
</tr>
<?php $previousValue = $val->LOAN_ID ?>
<?php endforeach; ?>
</table>
<input type="button" value="Print" id="prt" onclick="javascript:printDiv('printablediv')" />
</div>
i got javascript code here:
<script language="javascript" type="text/javascript">
function printDiv(divID) {
var divElements = document.getElementById(divID).innerHTML;
var oldPage = document.body.innerHTML;
document.body.innerHTML =
"<body>" +
divElements + "</body>";
$('#prt').hide();
window.print();
$('#prt').show();
document.body.innerHTML = oldPage;
}
You should use thead and tbody to print the table header on each page http://www.w3.org/TR/html4/struct/tables.html#edef-THEAD
Table rows may be grouped into a table head, table foot, and one or
more table body sections, using the THEAD, TFOOT and TBODY elements,
respectively. This division enables user agents to support scrolling
of table bodies independently of the table head and foot. When long
tables are printed, the table head and foot information may be
repeated on each page that contains table data.
If this doesn't work, the browser vendors doesn't implement the standard correctly.

Categories