Search data from the table using javascript - php

I am currently working on an application based on JavaScript and PHP. In my app, I have a table and a textbox - when I enter data in the textbox, the table should show the particular value that I typed. My current implementation does not work as I am not sure how to complete the search component - can anyone help?
<table name="tablecheck" class="DataTable" id="results" >
<thead>
<tr ><th> </th>
<th> </th>
<th><center><b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th></tr>
</thead>
<?php if(isset($records)) : foreach ($records as $row) : ?>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td>
<?php echo anchor('coursemaster_site/delete/'.$row->id, 'Delete',array('onClick'=>"return confirm('ARE YOU WANT TO DELETE..?')")); ?>
</td>
<td>
<input type=checkbox name="editcustomer[] " id="editcustomer[]" value="<?php echo $row->id ?>" >
</td>
<td >
<input class="inputwide span2 " type="text" onblur="upper(this)" name="course_code_<?php echo $row->id ?>" id=" course_code_<?php echo $row->id ?>" value="<?php echo $row->course_code ; ?> " >
</td>
<td>
<input class="inputmedium span2" type="text" name="course_name_<?php echo $row->id ?>" id="course_name_<?php echo $row->id ?>" value="<?php echo $row->course_name ; ?>" >
</td>
</tr>
</tbody>
<?php endforeach ; ?>
<?php endif ; ?>
</table>
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
<script>
function doSearch() {
var rowContainsSearchTerm, fullname;
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var searchTermMoreThanTwoCharsLong = v.length > 2;
for ( var i = 1; i < rows.length; i++ ) {
fullname = concatInputValues(rows[i].getElementsByTagName("input"));
if (fullname) {
rowContainsSearchTerm = fullname.indexOf(v) > -1;
if (searchTermMoreThanTwoCharsLong && rowContainsSearchTerm) {
rows[i].style.backgroundColor = "#00F";
} else {
rows[i].style.backgroundColor = "";
}
}
}
}
function concatInputValues(inputs){
var inputContents = "";
for (var j = 0; j < inputs.length; j++) {
inputContents = inputContents + inputs[j].value;
}
return inputContents;
}
</script>

Have you considered using JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:

Related

ARRAY_RAND always has the same output

well what it is is I have a task in php where I need to pick a card at random, then a button named "draw" which grabs another random card.
<td><b>Rectangle 10</b></br>
<p>Your card is: </p>
<?php
$cards = array("AC","AD","AH","AS","1C","1D","1H","1S",
"2C","2D","2H","2S","3C","3D","3H","3S","4C","4D","4H","4S",
"5C","5D","5H","5S","6C","6D","6H","6S","7C","7D","7H","7S",
"8C","8D","8H","8S","9C","9D","9H","9S","10C","10D","10H","10S",
"JC","JD","JH","JS","QC","QD","QH","QS","KC","KD","KH","KS"
);
$card = array_rand($cards, '1');
print_r($cards[$card]);
?>
<form>
<input type="button" value="Draw" onClick="window.location.reload()">
</form>
</td>
The code works on it's own, but in the whole page it doesn't, I'll paste the full page now.
<?php
$today = date_default_timezone_set('Europe/London');
$a = 3034;
srand($a);
?>
<table border='1'>
<tr>
<td><b>Rectangle 1</b></br>Rob Dorsett </br> 12007071 </br><?php echo $today = date('d/m/y')?></td>
<td><b>Rectangle 2</b></br><?php echo $addition = (3+4+5) ?></td>
</tr>
<tr>
<td><b>Rectangle 3</b></br> <?php srand(3034);
echo (rand()); ?> </td>
<td><b>Rectangle 4</b></br>
<?php for ($i=30;$i<=40;$i++){
if($i%2 == 0) {
echo $i. '</br>';}
}
?>
</td>
</tr>
<tr>
<td><b>Rectangle 5</b></br>
<form>
</br>
Enter four digits: </br>
<input name="input" />
</br><input type="submit" value="Sumbit" />
</form>
<?php
$x = $_GET['input'];
?>
</td>
<td><b>Rectangle 6</b></br>
<?php
if ($x%2 == 0){
echo 'Your number is even';
}
else
{
echo 'Your number is odd';
}
?>
</td>
</tr>
<td><b>Rectangle 7</b></br>
<form>
Enter a seed for a random number: </br>
<input type="text" name="random" /> </br>
<input type="submit" value="Generate" /> </br>
<?php
$r7 = $_GET['random'];
srand($r7);
echo rand();
?>
</form>
</td>
<td><b>Rectangle 8</b></br>
<?php
echo str_rot13('Example Rot13');
?>
</br>
<i>Example Rot13</i>
</td>
<tr>
<td><b>Rectangle 9</b></br>
<script type="text/javascript">
function rot13 (txt) {
var map = []
var tmp = "abcdefghijklmnopqrstuvwxyz"
var buf = ""
for (j = 0; j < tmp.length; j++) {
var x = tmp.charAt(j); var y = tmp.charAt((j + 13) % 26)
map[x] = y; map[x.toUpperCase()] = y.toUpperCase()
}
for (j = 0; j < txt.length; j++) {
var c = txt.charAt(j)
buf += (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' ? map[c] : c)
}
return buf
}
</script>
<script>var foo = rot13 ('Example Rot13')</script>
<p>Encoded: <script>document.write(foo)</script>
<p>Decoded: <script>document.write(rot13(foo))</script>
</td>
<td><b>Rectangle 10</b></br>
<p>Your card is: </p>
<?php
$cards = array("AC","AD","AH","AS","1C","1D","1H","1S",
"2C","2D","2H","2S","3C","3D","3H","3S","4C","4D","4H","4S",
"5C","5D","5H","5S","6C","6D","6H","6S","7C","7D","7H","7S",
"8C","8D","8H","8S","9C","9D","9H","9S","10C","10D","10H","10S",
"JC","JD","JH","JS","QC","QD","QH","QS","KC","KD","KH","KS"
);
$card = array_rand($cards, '1');
print_r($cards[$card]);
?>
<form>
<input type="button" value="Draw" onClick="window.location.reload()">
</form>
</td>
</tr>
</table>
You are feeding the srand() function with a static value, so you will always get the same result. Also, look at my last comment.
Removeing all srand(); makes your code work.
You should make some functions to get the random numbers and separate your PHP from your html/js. It would help the readabillity.

Auto updation of product price when its corresponding quantiy changes using jquery in a shopping cart

I am trying to develop just like a following siteenter link description here
Here when the user tries to purchase many items, his cart is displayed.And he can try to change the quantity of any item.When he changes the quantity of an item,the corresponding price of that item has to change automatically.It is done using jquery. I will provide my code here.
foreach( $_SESSION['r'] as $key=>$ar):
$cnt++;
?> <tr>
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center"> // Quantity is given as dropdownlist.Each list has seperate select id that is generated dynamivally.such as qty1,qty2,etc.
<select class="myclass" name="qty" id='qty<?php echo $cnt;?>' onChange="get_price(this.value,<?php echo $ar['Price']?>,<?php echo $cnt;?>)">
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay<?php echo $cnt;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="pprice" value='<?php echo $ar['Price'] ?>' class="input">
The next code is my jquery code
function get_price(val,price,cnt){
var price1 = val * price;
document.write(('<span id="priceDisplay"+cnt></span>\n'));
Here I am calculating the price when the quantity changes.But my problem is that I don't know how to display the calculated price in the appropriate column. variable cnt is the row id passed from php. Please help me.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function get_price(val,price,cnt)
{
var price1 = val * price;
$("#priceDisplay"+cnt).html(price1);
</script>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font> </b></center>
<?php
}
else
{
?>
<b><center><font color="green"> Your Shopping Cart!!</font></center> </b><br><br>
<form name="formview" action="ajaxview.php" method="post">
<?php $count=0; ?>
<table align="center" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="lightblue">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
foreach( $_SESSION['r'] as $key=>$ar):
$cnt++;
?> <tr>
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='qty<?php echo $cnt;?>' onChange=get_price(this.value,<?php echo $ar['Price']?>,<?php echo $cnt;?>,) >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay<?php echo $cnt;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="pprice" value='<?php echo $ar['Price'] ?>' class="input">
<td><input type='checkbox' name='remove' value='Remove' onCheck="$(this).closest('tr').remove();">
<?php $tt[]=$ar['Total'];?>
</tr>
<?php
endforeach;
?>
</table>
</form>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<b><center><div class="total"> Total:<span id="tot"><?php echo $count; ?></span></div></center></b>
<b><div class="cart">Your Cart:<span class="ycart"><?php echo $x; ?></span> </div></b>
Hope it helps,
function get_price(val,price,cnt){
var price1 = val * price;
document.getElementById('priceDisplay'+cnt).innerHTML =price1;
//$('#priceDisplay'+cnt).html(price1); //jquery
}
Using Jquery to acheive this,
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#"+IdForRemove).remove();
});
return false;
}
<table>
<?php
$cnt =0;
// session_start();
// $_SESSION['r'] = array('0'=>array('Name'=>'test 1','Price'=>'50.5','Id'=>'1', 'Quantity'=>'3'), '1'=>array('Name'=>'test 2','Price'=>'100','Id'=>'2', 'Quantity'=>'4'), '2'=>array('Name'=>'test 3','Price'=>'150','Id'=>'3', 'Quantity'=>'5'));
$CartR = $_SESSION['r'];
foreach($CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?>
<tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center"> // Quantity is given as dropdownlist.Each list has seperate select id that is generated dynamivally.such as qty1,qty2,etc.
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$ar['Quantity']){
$y='selected="selected"';
}
echo "<option value='".$i."' $y> $i</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td><input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>"> Remove
</tr>
<?php $cnt++; endforeach; ?>
</table>
Grand Total: <div id="GrandTotal"></div>
Create new file "RemoveCart.php" and below lines into that page,
<?php session_start();
if(isset($_POST['id'])){
$toBeRemove =$_POST['id'];
$CartR =$_SESSION['r'];
foreach($CartR as $key=>$Cart){
if($Cart['Id']==$toBeRemove){
unset($_SESSION['r'][$key]);
}
}
$CartR = $_SESSION['r'];
$Grandtotal =0;
foreach($CartR as $key=>$Cart){
$Grandtotal += $Cart['Quantity'] * $Cart['Price'];
}
echo json_encode(array('Grandtotal'=> "$Grandtotal"));
}
?>
Replace this:
document.write(('<span id="priceDisplay"+cnt></span>\n'));
With this:
document.getElementById("priceDisplay"+cnt).innerHTML=price1;
Using Jquery:
$("#priceDisplay"+cnt).html(price1);
You want it in jquery. Use
$("#id").html("hello World");
Change the id to the id you want to use. And the text as well

how to display two row of database value in textfield when user select one value from drop down list

When a user select the name using drop down list,the stock and price text field should automatically be filled.But it wont.
This is the code
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
var input = document.getElementById('price');
var input = document.getElementById('stock');
select.onchange = function(){
input.value = select.value;
}
</script>
i hope u guys can help.i've spent a week just to figured out the code.
Try this below code, below are some notes
Avoid using the Keywords like "name" in select box
Price and Stock Input element attribute are does not have spaced properly.
Avoid using Mysql_connect and start use PDO / MySQLi
Avoid presentational tags and start use css to acheive it like "text-align:center"
Currently its working as you expected without Ajax and its a quick workaround, I have added the value in a comma separated the both value by split function.
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
// echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
$option_value = $row['price'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
//var input = document.getElementById('price');
//var input = document.getElementById('stock');
var price = document.getElementById('price');
var stock = document.getElementById('stock');
select.onchange = function(){
// input.value = select.value;
var price_stock = select.value.split(',');
price.value = price_stock[0];
stock.value = price_stock[1];
}
</script>
How about this.......
Main File
<?php
$medOptions = "";
mysql_connect( "localhost", "root", "");
mysql_select_db( "arie");
$sql = mysql_query( "SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) !=0 ) {
while($row = mysql_fetch_assoc($sql)) {
$medOptions .= '<option value="' . $row['id'] . '">' . $row['name'] . '</option>\n';
}
}
?>
<form>
<table>
<tr>
<td class="label" width="55%">Medicine name</td>
<td width="45%">
<select name="med" id="med">
<option disabled="true" selected="true">--- Choose Medicine ---</option>
<?=$medOptions;?>
</select>
</td>
</tr>
<tr>
<td class="label">Price</td>
<td><input type="text" id="price" readonly="true" /></td>
</tr>
<tr>
<td class="label">Stock</td>
<td><input type="text" id="stock" readonly="true" /></td>
</tr>
</table>
CSS
table {
margin: 0 auto;
}
td {
text-align:center;
}
.label {
font-weight:bold;
}
Javascript
var select = document.getElementById('med');
// INSERT AJAX ROUTINE TO RETRIEVE PRICE AND STOCK LEVEL
var medPrice = document.getElementById('price');
var medStock = document.getElementById('stock');
select.onchange = function () {
medPrice.value = response.price;
medStock.value = response.stock;
};

arrange checkbox values in two columns

I have a form with check box values i want to arrange the checkbox in two columns instead of
one single long column.
How can i split it to two columns ?
Here is the code :
<form id="form" name="form" method="post" action="">
<table width="502" border="0">
<tr>
<td>
Name :
<input type="textbox" name="rcv_group_name" value="">
<input type="hidden" name="add" value="add" />
</td>
</tr>
<tr>
<td align="left">
<strong>HEADING</strong>
<?php
$q = "select * from Config_RCV";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0)
{
$k=0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM))
{
?>
<br> <input type="checkbox" name ="rcv_val[]" value ="<? echo $row[0];?>" /> <? echo $row[1];?>
<?
$k++;
}
}
?>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="Submit" id="Submit" value="Submit" style="background-color:#999" />
< /td>
<td height="26" align="left"> </td>
<td> </td>
</tr>
</table>
<form>
add another table and make 2 columns by splitting 2'nd result:
if (mysqli_num_rows($r) > 0) {
$k=0;
echo '<table><tr>';
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
?>
<td><input type="checkbox" name ="rcv_val[]" value ="<?php echo $row[0];?>" /> <?php echo $row[1];?> </td>
<?php
$k++;
if($k%2 == 0){
echo '</tr><tr>';
}
}
echo '</table>';
}
use your $k
if ($k%2==0){
echo "<br />";
}
instead of the lone now
Using tables like above will probably be better for looks
You could just add a second column to your table:
echo "<tr>";
$i = 0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
if ($i++%2==0) {
echo "</tr><tr>";
}
echo "<td>".$CELL_CONTENT_HERE."</td>";
}
echo "</tr>";

Checkbox Data Dynamically Save to Database on Click

I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.

Categories