javascript checkbox select all, unselect all, invert selection - javascript

I meet a problem with a script i'm doing. actually I gave something like that because I'm doing a mail box for my intranet.
<script type="text/javascript">
function GereChkbox(conteneur, a_faire) {
var blnEtat=null;
var Chckbox = document.getElementById('box-table-a').firstChild;
while (Chckbox!=null) {
if (Chckbox.nodeName=="INPUT")
if (Chckbox.getAttribute("type")=="checkbox") {
blnEtat = (a_faire=='0') ? false : (a_faire=='1') ? true : (document.getElementById(Chckbox.getAttribute("id")).checked) ? false : true;
document.getElementById(Chckbox.getAttribute("id")).checked=blnEtat;
}
Chckbox = Chckbox.nextSibling;
}
}
</script><form>
<table width="100%" border="0" id='box-table-a'>
<tr>
<th scope="col" width="15%"><strong>Expéditeur</strong></th>
<th scope="col" width="60%"><strong>Message</strong></th>
<th scope="col" width="10%"><strong>Date</strong></th>
<th scope="col" width="15%"><strong>Actions</strong></th>
</tr><?php $sql="SELECT * FROM `messages` WHERE `id_destinataire`='".$_SESSION['login']."' AND `trash`='0' ORDER BY id DESC LIMIT ".$premiereEntree.", ".$messagesParPage."" ;
$result=mysql_query($sql) or die(__LINE__.mysql_error().$sql);
$i=0;
while($data=mysql_fetch_assoc($result)) { ?>
<tr>
<td align="left"><?php $req="SELECT * FROM `gestionnaire` WHERE `login`='".$data['id_expediteur']."'";
$result2=mysql_query($req) or die(__LINE__.mysql_error().$req);
$expediteur=mysql_fetch_assoc($result2); ?><img src="<?php if (!empty($expediteur['urlavatar'])) {echo $expediteur['urlavatar']; } else {echo "images/noAvatar.gif" ;} ; ?>" width="50px" height="50px" /><br /><?php echo $expediteur['nom'].' '.$expediteur['prenom'] ; ?></td>
<td><?php if($data['lu']=='0') { echo '<p align="left"><img src="images/Gnome-Mail-Unread-32.png" width="24px" height="24px" /><strong> '.$data['titre'].'</strong></p>';
$nbChar = 150; // Nb. de caractères sans '...'
if(strlen($data['message']) >= $nbChar)
$message = substr($data['message'], 0, $nbChar).' [...]';
echo '<p align="left"><i>'.$message.'</i></p>';
}
else { echo '<p align="left"><img src="images/Gnome-Emblem-Mail-32.png" width="24px" height="24px" /><strong> '.$data['titre'].'</strong></p>';
$nbChar = 150; // Nb. de caractères sans '...'
if(strlen($data['message']) >= $nbChar)
$message = substr($data['message'], 0, $nbChar).' [...]';
echo '<p align="left"><i>'.$message.'</i></p>';} ;
?></td>
<td><?php echo date('d-m-Y H:i',strtotime($data["date"])) ; ?></td>
<td><img src="images/email_open.png" alt="Lire le message" width="24px" height="24px" border="0" /> <img src="images/Gnome-Mail-Forward-32.png" alt="Transférer le message" width="24px" height="24px" border="0" /> <img src="images/mail-trash.png" alt="Supprimer ce message" width="24px" height="24px" border="0" /> <input type="checkbox" name="action[<?php echo ++$i; ?>]" id="checkbox<?php echo $i; ?>" /></td>
</tr>
<?php } ; ?>
</table>
<table width="100%" border="0">
<tr>
<td>Actions: <input type="button" value="Tout cocher" onClick="GereChkbox('div_chck','1');">
<input type="button" value="Tout décocher" onClick="GereChkbox('div_chck','0');">
<input type="button" value="Inverser la sélection" onClick="GereChkbox('div_chck','2');"></td>
<td> </td>
</tr>
</table>
</form>
In fact it does not really work because of the script and I have no error messages in the console.
Thank you verry much in advance for your help.
Kind regards.

Anyway, here's a function that toggles / checks / unchecks any checkboxes given to it:
function changeCheckboxes(list, value){
for(var i = list.length - 1 ; i >=0 ; i--){
list[i].checked = (typeof value === 'boolean') ? value : !list[i].checked ;
}
}
It accepts a nodelist or array of checkboxes as the first parameter. Use it as follows...
Toggle Checkboxes:
changeCheckboxes(allCheckboxes);
Check Checkboxes:
changeCheckboxes(allCheckboxes, true);
Uncheck Checkboxes:
changeCheckboxes(allCheckboxes, false);
To get allCheckboxes, you can do this:
var inputs = document.getElementsByTagName('input');
var allCheckboxes = [] ;
for (var j = inputs.length-1 ; j >= 0 ; j--){
if (inputs[j].type === 'checkbox'){
allCheckboxes.push(inputs[j]);
}
}

Related

Javascript is not doing sum of all records

I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.
What is the issue i cannot understand. I have tried by moving code in the java but no use.
Suppose i have 2 items.
Item1 total is = 100
Item2 total is = 200
Total should be 300 not only the 1 items total.
Below is my code.
Thanks in advance
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<table class="table mg-bottom-45 refresh" id="myTable">
<thead>
<tr>
<th class="product-cart-price"><span>PRICE</span></th>
<th class="product-cart-price"><span>TOTAL</span></th>
</tr>
</thead>
<tbody>
<?php
include ('inc/db.php');
$citem = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
$userID = $cifetch['user_id'];
?>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="<?php echo $cifetch['price']; ?>"
value="<?php echo $cifetch['price']; ?>" class="un pricex" />
</td>
<?php } ?>
<td class="totalAmount"></td>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = '';
$('#myTable > tbody > tr').each(function() {
var quantityx = $(this).find('.quant').val();
var pricex = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantityx * pricex).toFixed(3);
sumx += amountx;
});
$('.totalAmount').text(sumx);
}
});
</script>
First, please make sure that your loop is running multiple times (same number of products in cart).
$('#myTable > tbody > tr').each(function() {})
so that the above loop iterate exact number times as per required.
You should make some changes in code as follows:
var sumx = 0.00;
and in loop code should be
sumx += parsefloat(amountx);
So here is the solution with some changes in my code.
Now it is working perfectly as required. It is doing the sum of all items and everything what i want.
<table class="table mg-bottom-45 refresh" id="myTable">
<tbody>
<?php
$i = 0;
//error_reporting(0);
$ses_mem = 1;
include ('inc/db.php');
$citem = "select id, user_id, qty, org_price from orders_temp
where user_id = '".$ses_mem."' and status = 1
order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
?>
<tr>
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = 0.000;
var quantity;
$('#myTable > tbody > tr').each(function() {
quantity = $(this).find('.quant').val();
var price = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantity * price);
var munterx = amountx.toFixed(3);
sumx += amountx;
$(this).find('.amountx<?php echo $orderID; ?>').text('' + munterx);
});
var sumxx = sumx.toFixed(3);
$('.total').text(sumxx);
}
});
</script>
<td class="single-qty" style="border: 0;">
<input id="<?php echo $orderID; ?>" name="quantity" type="text"
data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-price pricex" data-price="<?php echo $cifetch['org_price']; ?>">
</td>
<td class="amountx<?php echo $orderID; ?>">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="table">
<tbody>
<tr>
<td>Sub Total (RS)</td>
<td class="text-right"
style="text-shadow: 2px 2px 3px #999999; font-weight: bold;
color: black; direction: rtl;">
<span class="total">
</span>
</td>
</tr>
</tbody>
</table>

Pull JavaScript Spinner Value from Table into Email

I have a multiple column table with one of the columns being a checkbox. I can check different rows and then hit a "Checkout" button and it will display the corresponding selected table row data in the body of an email.
Whenever a checkbox is checked, it also displays an extra column Quantity # which contains a spinner where the user can either type in a number or use the up/down arrows to select a number. However, when I enter a number and then hit the "Checkout" button, the value is always displayed as undefined.
I am getting the value of the spinner in my console but am unsure of how to get it displayed on my email. How can I get it so that the value will be read and correctly displayed on the email body?
HTML:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<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" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td 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 class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content" data-spinner="<?php echo intval ($row['ID'])?>"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript to send data to email:
function sendMail() {
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
$('table tr input[name="check"]:checked').each(function(){
var current_tr = $(this).parent().parent();
var data = current_tr.find('.loc').data('loc');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.rp-code').data('rp-code');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.sku').data('sku');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.special-id').data('special-id');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.description').data('description');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.quantity').data('quantity');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.unit').data('unit');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.quantity_num').data('spinner');
body += encodeURIComponent(data) + '\xa0\xa0';
body += '%0D%0A';
});
body += '';
link += body;
console.log(link);
window.location.href = link;
}
JavaScript for spinner:
$(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;
}
var test = ui.value;
sessionStorage.setItem("test", JSON.stringify(test));
var testtrue = sessionStorage.getItem("test");
console.log(JSON.parse(testtrue));
}
});
});
});
As far as I can tell, you want to get the current value of the so-called spinner, which is given by :
$(selector).spinner('value')
So, in full, something like this should build the required string :
function sendMail() {
var dataItems = [
{ 'clss':'.loc', 'prop':'loc' },
{ 'clss':'.rp-code', 'prop':'rpCode' },
{ 'clss':'.sku', 'prop':'sku' },
{ 'clss':'.special-id', 'prop':'specialId' },
{ 'clss':'.description', 'prop':'description' },
{ 'clss':'.quantity', 'prop':'quantity' },
{ 'clss':'.unit', 'prop':'unit' }
];
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=";
link += $('#merchTable tr input[name="check"]:checked').closest('tr').get().map(function(tr) {
var str = dataItems.map(function(item) {
return encodeURIComponent($(tr).find(item.clss).data(item.prop)) + '\xa0\xa0';
}).join('');
str += encodeURIComponent($(tr).find('.spinner').spinner('value')) + '\xa0\xa0';
return str;
}).join('') + '%0D%0A';
console.log(link);
window.location.href = link;
}
Note the use of .map() (twice) to map an Array of objects to Array of strings, and .join('') to put the pieces together.

How to Display All Values in Email Body that are Checked Regardless if Visible

I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
I originally bring in the top 100 rows to keep the info to a minimum for the user. I also have a search functionality where the user can search for specific rows. The user can maneuver throughout different searches and still keep all of the checkboxes checked with session storage. However, when a user hits "Checkout" the body of the email only displays the table rows that are checked and currently visible on the page.
So, if a user searches for a table row and checks it, but then navigates back to the original top 100 rows by clicking home, that row would not display on the email because it is not displayed in the top 100.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
JavaScript that sends information to email body:
function sendMail() {
var dataItems = [
{ 'clss':'.loc', 'prop':'loc' },
{ 'clss':'.rp-code', 'prop':'rpCode' },
{ 'clss':'.sku', 'prop':'sku' },
{ 'clss':'.special-id', 'prop':'specialId' },
{ 'clss':'.description', 'prop':'description' },
{ 'clss':'.quantity', 'prop':'quantity' },
{ 'clss':'.unit', 'prop':'unit' }
];
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=";
link += $('#merchTable tr input[name="check"]:checked').closest('tr').get().map(function(tr) {
var str = dataItems.map(function(item) {
return encodeURIComponent($(tr).find(item.clss).data(item.prop)) + '\xa0\xa0';
}).join('');
str += encodeURIComponent($(tr).find('.spinner').spinner('value')) + '%0D%0A';
return str;
}).join('') + '%0D%0A';
console.log(link);
window.location.href = link;
}
JavaScript that includes code to keep all checkboxes checked throughout session:
$(function(){
var showQuantityHeader = false;
$(':checkbox').each(function() {
// Iterate over the checkboxes and set their "check" values based on the session data
var $el = $(this);
//console.log('element id: ',$el.prop('id'),' sessionStorage[id]: ',sessionStorage[$el.prop('id')]);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
if ($el.prop('checked')) {
//show the quantity cell in the column under header with class num
$el.closest('tr').find('td.quantity_num').toggle(this.checked);
showQuantityHeader = true;
setupSpinner(this);
var quantity = sessionStorage['value_'+$el.prop('id')];
if (quantity) {
$el.closest("tr").find(".spinner" ).spinner( "value", quantity );
}
}
});
if (showQuantityHeader) {
$('#merchTable').find('th.num').show();
//console.log('header with class num: ',$('#merchTable').find('th.num'));
}
$('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');
});
});
HTML Table:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<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" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td 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 class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input disabled="true" type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>

Displaying images with selected options

I am making a site for questions and answers in which few multiple choice questions will be displayed and the user would have to select radio buttons to answer the questions. After submitting, right and wrong answers would displayed and user would be given the option of seeing the correct answer.
In this page for seeing correct answers what I want to do is to show an image of tick mark for the correct option and a cross image for all other wrong options. But I am facing problems in writing the logic.
This is what I have done till now.
This page is for selecting which image is to be displayed
<?
session_start() ;
$wrong = array() ;
if( !empty($_SESSION['wrongAnswer'] ) ) {
$wrong = $_SESSION['wrongAnswer'] ;//wrongAnswer array has
//ids of wrongly answered
//questions
session_destroy() ;
}
if( !empty($_POST['wrongAnswer'] ) ) {
$wrong = $_POST['wrongAnswer'] ;
}
$i = 0 ;
$quesID = "";
$question = "" ;
require_once "connection.php";
foreach ($wrong as $n) {
<? $query = "SELECT * FROM answers WHERE question_id = '$n' " ;
if($result = $mysqli->query( $query ) ) {
if( $row = $result->fetch_object() ){
$answer = $row->answer ;
// $count++;
}
else
echo "Couldn't tally answer " . $mysqli->error ;
}
else
echo "Error executing query" . $mysqli->error ;
//<----- THIS IS WHERE THE WRONGLY ANSWERED QUESTIONS WILL BE DISPLAYED WITH IMAGES AS MENTIONED BEFORE ------>//
$query = "SELECT * FROM questions WHERE questionid='$n' " ;
$i ++ ;
if( $result = $mysqli->query( $query ) ) {
$count= $result->num_rows ;
echo '<form name = "checkans.php" action = "checkans.php" method = "POST" >' ;
$row = $result->fetch_object() ;
// $i++ ;
$quesID = $row->questionid ;
$question = $row->question ;
$quesID = $row->questionid ;
$query2 = "SELECT option1,option2,option3,option4 FROM options WHERE questionid='$quesID'" ;
if($result2 = $mysqli->query($query2) ) {
if($row2 = $result2->fetch_object() ) {
$option1 = $row2->option1 ;
$option2 = $row2->option2 ;
$option3 = $row2->option3 ;
$option4 = $row2->option4 ;
?>
<table border="0" cellpadding="0" cellspacing="0">
<? echo "<div id = $row->questionid name = boxs>" ; ?>
<th> <h2> <? echo $i .")" ; ?> </h2> </th>
<th> <h2> <?echo $row->question ;?> </h2> </th>
<tr> <input type="hidden" name="quesID[]" id="<? echo $quesID ; ?>" value="<? echo $quesID ; ?>">
<div id = "options">
<td>
<span id = "1">
<img id = "image" height="50px" width="50px">
</td>
<td>
<label>
<? echo $option1 ;?>
</label>
</td>
</span>
<td>
<span id = "2">
<img id = "image" height="50px" width="50px">
</td>
<td>
<label>
<? echo $option2 ;?>
</label>
</td>
</span>
<td>
<span id = "3">
<img id = "image" height="50px" width="50px">
</td>
<td>
<label>
<? echo $option3 ;?>
</label>
</td>
</span>
<td>
<span id = "4">
<img id = "image" height="50px" width="50px">
</td>
<td>
<label>
<? echo $option4 ;?>
</label>
</td>
</div>
</span>
</div>
</tr>
</table>
</section>
<?
}
else
echo "No options available for this question" ;
}
}
?>
<script type="text/javascript">
var i = 0
for(i=1; i <= 4; i++) {
var y = document.getElementById(i);
//alert(y.childNodes)
var x = document.getElementById("image");
if( y.id == (<?echo $answer ; ?>) ) {
x.src = "correct.png" ;
}
else
x.src = "wrong.jpg" ;
}
}
</script>
<?
}
?>
Thing wrong with my code is that it just displays image for only 1 question and that too with the wrong option.

How to retain in the same selection after refresh?

How to retain with the same selection in dropdown when refresh or after I submit or delete?
I have this code below that select value from database. I want to back with the same value in select dropdown after I refresh or I submit the form or delete records.
bid.php
<html>
<head>
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('bid_list.php?q=' + str)
}
</script>
</head>
<body onload=showUser(str="ALL")>
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT bid FROM procurement WHERE bid LIKE '13-___' OR bid LIKE '1_-___' OR bid LIKE '2_-___' GROUP BY bid ORDER BY bid");
$option = '';
while($row = $result->fetch_assoc())
{
$option .= '<option value = "'.$row['bid'].'">'.$row['bid'].'</option>';
}
?>
<select name="users" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php echo $option; ?>
</select>
<div id="txtHint">
</div>
</body>
</html>
bid_list.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$q = $_GET["q"];
$where = '';
if ( $q != 'ALL' ) {
$where = " WHERE bid='$q' ";
}
$result1 = $mysqli->query("
SELECT bid, item_name, item_description, unit, unit_cost, quantity, supplier, po_number, po_date, counter, SUM(unit_cost*quantity) AS total_amount
FROM procurement
$where
GROUP BY counter ORDER BY bid
");
echo'<table id="tfhover" cellspacing="0" class="tablesorter" style="text-transform:uppercase;">
<thead>
<tr>
<th colspan="3" id="none" style="cursor: default;"></th>
<th title="Item Name">Item Name</th>
<th title="Item Description">Description</th>
<th title="Example : Pc, Pcs, Box and Etc.">Unit</th>
<th title="Item Price">Unit Cost</th>
<th title="Total Item Quantity">QTY</th>
<th title="Total Price">Total Amount</th>
<th title="Name of Supplier">Supplier</th>
<th title="Purchase Order Date">PO Date</th>
<th title="Purchase Order #">PO #</th>
<th id="none" style="cursor: default;"></th>
</tr>
</thead>';
echo'<tbody>';
while($row = $result1->fetch_assoc()){
if($row['bid'] != '')
{
echo'<tr>
<td align="center"><img src="images/del.png" border="0" width="10" height="10" title="Delete"></td>
<td align="center"><a class="fancybox" href="edit.php?pn='.$row["counter"].'"><img src="images/edit.png" border="0" width="10" height="10" title="Edit"></a></td>
<td align="center"><a class="fancybox" href="comments.php?pn='.$row["counter"].'"><img src="images/remarks.png" border="0" width="10" height="10" title="Remarks and Notes"></a></td>
<td>'.$row['item_name'].'</td>
<td>'.$row['item_description'].'</td>
<td>'.$row['unit'].'</td>
<td>'.number_format($row['unit_cost'], 2, '.', ',').'</td>
<td>'.$row['quantity'].'</td>
<td>'.number_format($row['total_amount'], 2, '.', ',').'</td>
<td>'.$row['supplier'].'</td>
<td>'.$row['po_date'].'</td>
<td>'.$row['po_number'].'</td>
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$row['counter'].'"></td>
</tr>';
}
}
echo "</tbody></table>";
use a jquery ajax call, and update the DOM when your ajax call succesfully returns. see http://api.jquery.com/jQuery.ajax/
AJAX can be used for interactive communication with a database, please check the web site here : http://www.w3schools.com/php/php_ajax_database.asp
i believe that is what you need.

Categories

Resources