Keep checkboxes checked when the form is submitted - javascript

I have the following form with checkboxes.
<?php
include 'connection.php';
$sql="SELECT * FROM `tbl`";
$query=mysqli_query($connect,$sql);
echo "<table border='2px'>
<thead>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</thead>
<tbody>
<form method='POST'>";
while($res=mysqli_fetch_assoc($query)){
$id=$res['id'];
echo"<tr>
<td>{$res['id']}</td>
<td>{$res['title']}</td>
<td>{$res['name']}</td>
<td><input type='checkbox' name='doing[]' value='".$res['id'].$res['title'].$res['name']."'></td>
<td><input type='checkbox' name='done[]' value='".$res['id'].$res['title'].$res['name']."'></td>
</tr>";
}
echo "<input type='submit' value='OK' name='btn'>
</form>
</tbody>
</table>";
?>
How do I make the checkboxes keep their checked state when the form is submitted?

I assume that you don't want both doing and done to be checked at the same time, so I replaced the checkboxes with radio buttons because that is their intended behavior.
I changed the names and values for the radio buttons so that they can be easily accessed in PHP, and from the code you've supplied it doesn't look appear as if you're using the names and values afterwards anyways.
I cleaned up the markup and script layout to make it more readable.
Please let me know if I have deviated too far from the intent of your original code.
Note: This will display the posted values, but it will not save those values to the database.
(Demo)
<?php
include('connection.php');
$sql = "SELECT * FROM `tbl`";
$query = mysqli_query($connect,$sql);
function get_checked ( $id ) {
if ( isset($_POST) && isset($_POST['checked'][$id]) ) {
return $_POST['checked'][$id];
}
return false;
}
?>
<form method="post">
<table border="2px">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<?php while ( $res = mysqli_fetch_assoc ( $query ) ): ?>
<?php $checked = get_checked ( $res['id'] ) ?>
<tr>
<td><?= $res['id'] ?></td>
<td><?= $res['title'] ?></td>
<td><?= $res['name'] ?></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="doing" <?= $checked === "doing" ? 'checked' : '' ?>></td>
<td><input type="radio" name="checked[<?= $res['id'] ?>]" value="done" <?= $checked === "done" ? 'checked' : '' ?>></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<input type='submit' value='OK' name='btn'>
</form>

You can try to use this code.Hope this will work (Also try to use mysqli or PDO):
<?php
include 'connection.php';
$sql="SELECT * FROM `tbl`";
$query=mysqli_query($connect,$sql);
echo "<table border='2px'>
<thead>
<th>ID</th>
<th>Title</th>
<th>Name</th>
<th>Doing</th>
<th>Done</th>
</thead>";
echo "<form method='POST'>";
echo "<tr>";
$s=0;
while($res=mysqli_fetch_assoc($query)){
$id=$res['id'];
$doing_v="";
$done_v="";
$c_doing="";
$c_done="";
if(isset($_POST['doing'][$s])){
$doing_v=$_POST['doing'][$s];
}
if(isset($_POST['done'][$s])){
$done_v=$_POST['done'][$s];
}
if($doing_v=='".$res['id'].$res['title'].$res['name']."'){
$c_doing="checked";
}
if($done_v=='".$res['id'].$res['title'].$res['name']."'){
$c_done="checked";
}
echo" <td>{$res['id']}</td>
<td>{$res['title']}</td>
<td>{$res['name']}</td>
<td><input type='checkbox' name='doing[]'
value='".$res['id'].$res['title'].$res['name']."' ".$c_doing." ></td>
<td><input type='checkbox' name='done[]'
value='".$res['id'].$res['title'].$res['name']."' ".$c_done." ></td>
</tr>";
$s++;
}
echo "</table>";
echo "<input type='submit' value='OK' name='btn'>";
echo "</form>";
?>

Related

Sweetalert won't show but it will update

I want to show a sweetalert after clicking the set button but it won't function. This is my index page and the set button can function but it won't show the sweet alert. what might be the problem and what should I do?
index.php
<form method='post' action='updataStatus.php'>
<button type='submit' name='but_update' class="inline-block float ml-2 mt-1 btn-group pull-right btn-danger btn-sm">SET</button><button type="submit" id="dataExport" name="dataExport" value="Export to excel" class="inline-block float ml-2 mt-1 btn-group pull-right btn-info btn-sm">Export</button>
<div class="table-responsive">
<br>
<tbody><table class="table table-hover table-bordered" id="sampleTable2">
<thead>
<tr>
<th><input type="checkbox" class="select-all checkbox" name="select-all" id="checkAll" /></th>
<th>Name</th>
<th>Scholarship Program</th>
<th>Course</th>
<th>Semester</th>
<th>Allowance</th>
</tr>
</thead>
<?php
require_once "connection.php";
$query = "SELECT * FROM allowance";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result) ){
$id = $row['id'];
$Name = $row['Name'];
$Scholarship = $row['Scholarship'];
$Course = $row['Course'];
$Semester = $row['Semester'];
$statusAllowance = $row['statusAllowance'];
?>
<tr>
<!-- Checkbox -->
<td><input type='checkbox' name='update[]' value='<?= $id ?>' ></td>
<td><p name="Name"><?php echo $row['Name']; ?></p></td>
<td><p name="Scholarship"><?php echo $row['Scholarship'] ?></p></td>
<td><p name="Course"><?php echo $row['Course'] ?></p></td>
<td><p name="Semester"><?php echo $row['Semester'] ?></p></td>
<td><p name='statusAllowance_<?= $id ?>'><?php echo $row['statusAllowance'] ?></td>
</tr>
<
?php
}
?>
</table>
</tbody>
<?php
if(isset($_SESSION['success']) && $_SESSION['success'] !='')
{
?>
<script type="text/javascript">
swal({
title: "<?php echo $_SESSION['success']; ?>",
icon: "<?php echo $_SESSION['status_code']; ?>",
button: "yissh",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
This is my code on the edit part and this works, only the alert won't show up.
updataStatus.php
<?php
require_once "connection.php";
if(isset($_POST['but_update'])){
if(isset($_POST['update'])){
foreach($_POST['update'] as $id){
$statusAllowance = 'Received';
if($statusAllowance != '' ){
$updateUser = "UPDATE allowance SET statusAllowance='".$statusAllowance."' WHERE id=".$id;
$query_run = mysqli_query($conn,$updateUser);
if($query_run){
$_SESSION['success'] = "YOUR DATA UPDATED";
header('Location: tracking.php');
}else{
$_SESSION['success'] = "YOUR DATA IS NOT UPDATED";
header('Location: tracking.php');
}
}
}
}
}
?>
considering you have not implemented another function to call sweetalert; by default, it should be Swal.fire({}) not just swal({})
https://sweetalert2.github.io/

Delete data from database using PHP & JavaScript

I am working on a PHP file. I am trying to make a table that shows the list of products from database. There will be also a button for deleting any product. I have used javascript for deleting products from database. I have written the code and could not find anything wrong. When I click delete button, it shows me the confirmation box, but does not delete the product. Here is the code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("grocery_shop",$con);
error_reporting(E_ALL^E_NOTICE);
session_start();
$sql = mysql_query("select * from products");
if($_GET['did']){
mysql_query("delete from products where product_id='$_GET[did]'");
header("Location: product.php");
}
?>
<table border="1px" style="width:100%">
<tr>
<th>Serial No</th>
<th>Product Name</th>
<th>Product Type</th>
<th>Quantity</th>
<th>Price</th>
<th>Delete Product</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$i=1;
while ($u = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $u['product_name'];?></td>
<td><?php echo $u['product_type'];?></td>
<td><?php echo $u['quantity'];?></td>
<td><?php echo $u['price'];?></td>
<td><?php echo "Delete";?></td>
</tr>
<?php
$i++;
}
?>
<script>
function delproduct(id){
var msg = confirm("Are you sure you want to delete this product?");
if (msg) {
window.location = "product.php?did="+product_id;
}
}
</script>
</table>
The problem is in your javascript, the product_id doesn't exist
if (msg) {
window.location = "product.php?did="+id;
}
For debugging purposes try to replace this with your code and let us know the error message you get.
if($_GET['did']){
mysql_query("delete from products where product_id='".$_GET['did']."'");
echo "delete from products where product_id='".$_GET['did']."'";
echo mysql_errno() . ": " . mysql_error() ;
die();
//header("Location: product.php");
}
additionally also try to run the query without the single quotes, i am assuming product_id is an integer.
so mysql_query("delete from products where product_id=".$_GET['did']);
You forgot the '' around did in $_GET[did]:
mysql_query("delete from products where product_id='{$_GET['did']}'");
Also, as #chris85 noted, is not a good idea to use $_GET or $_POST directly, remember to sanitize these values before using it in a query.
$did = filter_input(INPUT_GET, 'did', FILTER_SANITIZE_NUMBER_INT);
mysql_query("delete from products where product_id={$did}");
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("grocery_shop",$con);
error_reporting(E_ALL^E_NOTICE);
session_start();
$sql = mysql_query("select * from products");
if($_GET['did']){
mysql_query("delete from products where product_id='$_GET[did]'");
header("Location: product.php");
}
?>
<table border="1px" style="width:100%">
<tr>
<th>Serial No</th>
<th>Product Name</th>
<th>Product Type</th>
<th>Quantity</th>
<th>Price</th>
<th>Delete Product</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$i=1;
while ($u = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $u['product_name'];?></td>
<td><?php echo $u['product_type'];?></td>
<td><?php echo $u['quantity'];?></td>
<td><?php echo $u['price'];?></td>
<td><?php echo "Delete";?></td>
</tr>
<?php
$i++;
}
?>
<script>
function delproduct(id){
var product_id = id;
var msg = confirm("Are you sure you want to delete this product?");
if (msg) {
window.location = "product.php?did="+product_id;
}
}
</script>
</table>
You should try: delproduct($u[product_id]) instead of delproduct(id=$u[product_id])
mysql_query("delete from products where product_id='".$_GET['did']."'");
while ($u = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $u['product_name'];?></td>
<td><?php echo $u['product_type'];?></td>
<td><?php echo $u['quantity'];?></td>
<td><?php echo $u['price'];?></td>
<td><?php echo "Delete";?></td>
</tr>
<?php
$i++;
}

How to get value table row value using jquery/ajax

<?php
include "config.php";
// Fetch the data
$con = mysql_query("select * from product");
?>
<div style=" height:250px; overflow:auto;">
<table class="table table-striped table-bordered dTableR" id="ajxtable">
<tr>
<th>Jobno</th>
<th>Product</th>
<th>Qty</th>
<th>Designed by</th>
<th>Action</th>
</tr>
<?php
while ($row = mysql_fetch_array($con)) {
$id = $row['id'];
$pcode = $row['pcode'];
$lproduct = $row['lproduct'];
$mrprate = $row['mrprate'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $lproduct; ?></td>
<td><?php echo $mrprate; ?></td>
<td><?php echo "admin"; ?></td>
<td><input type="button" id="addmorePOIbutton1" style="width:25px;" value="+" onClick=""/>
<input type="button" id="delPOIbutton1" style="width:25px;" value="-" onClick=""/></td>
</tr>
<?php
}
?>
</table>
</div>
This is ajax page. Below table is auto refreshed every 5 seconds.
My doubt is how to get that particular row value.
When i click table row + button, get these particular row values, and place to index page text box and this '+' button also hide.
Kindly suggest any jquery or ajax code for adding below code.
I am new to jquery ,,anybody help me with sample code..that would help me greately. Thanks in advance
$(document).ready(function () {
$('#yourtablename tr').click(function (event) {
alert($(this).attr('id')); //trying to alert id of the clicked row
});
});
Above code may be help you and another solution is:
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});

Onchange pop out error javascript

I try to auto calculate the input without any button. I try to do it with javascript onchange function.However, javascript keep pop out the error and I do not know how to solve it.
This is the error : Uncaught SyntaxError: Unexpected identifier
below is my code :
<!DOCTYPE html>
<html>
<script>
function jsfunction()
{
var x=document.getElementById("qty1");
var y =document.getElementById("price1");
var z =document.getElementById("total1");
alert("You entered: " + y.value);
}
</script>
<body>
<?php
$item=array("A"=>"10","B"=>"11","C"=>"12","D"=>"13");
$var=1;
$total=0;
$gtotal=0;
?>
<table border=1 width='600'
<tr>
<th>No</th>
<th>item</th>
<th>Check</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>";
<?php
foreach($item as $myItem=>$pricetag){
echo "<tr>";
echo "<td>".$var."</td>";
echo "<td>".$myItem."</td>";
$price = "price". $var;
$qty = "qty". $var;
$total = "total". $var;
?>
<td><input type="checkbox" id="chkbox" name="chkbox"/></td>
<td><input type="text" name=<?php $price ?> id=<?php $price ?> size =1/><?php echo $price ?> </td>
<td><input type="text" onchange="jsfunction() name=<?php $qty ?> id=<?php $qty ?> size =1/><?php echo $qty ?></td>
<td><input type="text" name=<?php $total ?> id=<?php $total ?> size =1/></td>
<?php
$var++;
}?>
</table>
</form>
</body>
</html>
Well, there are a few problems:
You never have the closing > of the <table> tag:
<table border=1 width='600' => <table border=1 width='600'>
You have a random "; when the code is not even PHP nor JavaScript:
<th>Total</th>
</tr>";
You are using the PHP tag as an echo tag:
<?php $price ?> => <?php echo $price ?>
You never close the double quotes when calling your JavaScript function:
onchange="jsfunction() => onchange="jsfunction()"
EDIT:
If your name property is NULL, it may cause problems because the id will be set to the name, so you should wrap the name in quotes (Just to be safe you should probably do it with everything including id, size, name, etc.):
name=<?php $price ?> => name="<?php $price ?>"
Among other things, this line has a JavaScript error:
<td><input type="text" onchange="jsfunction() name=<?php $qty ?> id=<?php $qty ?> size =1/><?php echo $qty ?></td>
It should probably be:
<td><input type="text" onchange="jsfunction()" name="<?php echo $qty; ?>" id="<?php echo $qty; ?>" size="1" /><?php echo $qty; ?></td>
You must use the echo function to print out a PHP variable to the HTML.
Also, throughout your HTML form, don't forget to wrap all the input parameter values in quotation marks (" ").
What is the value of $price? You are getting element's by their id, e.g. price1, but if $price is not equal to the string 'price1' it will fail to get an element by that id and your javascript will be calling into a null value.

Javascript comparison for a table row to highlight a row in red (CakePHP)

How do I find the right approach to getting this comparison to work? I've tried all kinds of approaches. I even used ids, but they don't respond. If I do this "gumboots" string check though, it does work. "gumboots" was just a value for a product name that existed somewhere on the table. This is how I know I do not need PHP at all for this, despite the tables displayed in PHP in the Index view below. Any idea? I would appreciate it.
Here's the javascript
$('#example tbody tr td').each(function()
{
//var p_no_in_stock = parseInt($('#p_no_in_stock')).val();
//var p_reorder_quantity = parseInt($('#p_reorder_quantity')).val();
var p_no_in_stock = parseInt(document.getElementById('p_no_in_stock')).value;
var p_reorder_quantity = parseInt(document.getElementById('p_reorder_quantity')).value;
//if ($product['Product']['p_no_in_stock'].val() < $product['Product']['p_reorder_quantity'].val())
if ($(this).text() == "gumboots")
//if ($(this).p_no_in_stock < $(this).p_reorder_quantity)
{
//$("#row_" +" td").effect("highlight", {}, 1500);
$(this).closest('tr').attr('style','background-color:red');
$(this).parent().css('background-color','red');
$(this).parent().attr('style','background-color:red');
$(this).parent().addClass('highlight');
$(this).parent().css('font-weight','bold');
}
});
And this is the application in a View called Products.index
<div class="active">
<h2><?php echo __('Products'); ?></h2>
<table cellpadding="0" cellspacing="0" class="table table-striped table-bordered" id ="example">
<tr>
<th><?php echo $this->Paginator->sort('p_name', 'Name'); ?></th>
<th><?php echo $this->Paginator->sort('category_name', 'Category'); ?></th>
<th><?php echo $this->Paginator->sort('p_no_in_stock','No. in Stock'); ?></th>
<th><?php echo $this->Paginator->sort('p_reorder_quantity', 'Re-order Quantity'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo h($product['Product']['p_name']); ?></td>
<td> <?php echo $this->Html->link($product['Category']['category_name'],
array('controller' => 'categories', 'action' => 'view', $product['Category']['id'])); ?>
</td>
<td id = "p_no_in_stock" type ="number" ><?php echo h($product['Product']['p_no_in_stock']); ?> </td>
<td id ="p_reorder_quantity" type ="number" ><?php echo h($product['Product']['p_reorder_quantity']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $product['Product']['id']), array('class' => 'btn btn-mini'), __('Are you sure you want to delete # %s?', $product['Product']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Thanks in advance.
Is this what you're asking?
http://jsfiddle.net/SinisterSystems/z9SE7/1/
HTML:
<table>
<tr>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
</tr>
<tr>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
</tr>
</table>
CSS:
tr:hover td {
background:#F00;
}
I am sending you mine code, please modify it accordingly....
The PHP Code is as -
<?php
if($num>0)
{
echo '<table width="100%" id="dep_table" style="margin-top:10px;" cellspacing="1" cellpadding="2" border="0">';
echo '<tr bgcolor="#4682B4">';
echo '<th>Editor</th>';
echo '<th>Department Id</th>';
echo '<th>Department Name</th>';
echo '</tr>';
$i=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$i++;
if($i % 2 == 0)
{
$bgcolor= "#6AA2C3";
}
else
{
$bgcolor= "#A2B5CD";
}
//extract row, this will make $row['firstname'] to just $firstname only
extract($row);
//creating new table row per record
echo "<tr bgcolor='$bgcolor' id='$DeptId' name='edit_tr'>";
echo '<td id="edit"><input id="edit" type="radio" name="deptid" value="DeptId" ?></td>';
echo "<td class='format'>{$row['DeptId']}</td>";
echo "<td class='format'>{$row['DeptName']}</td>";
echo "</tr>";
}
echo "</table>";
}
echo "</div>";
The JS for corresponding code is as -
$(document).ready(function() {
row_color();
$('#dep_table tr').click(function(e) {
$(this).find('td input:radio').prop('checked', true);
/* submit_fxn();
$('#form_ndesg').submit(function(e) {
return false;
});*/
});
});
//******* 1 Div Fade In/Out effect *******
function row_color(){
$('#dep_table tr').not(':first').hover(function(){
$(this).addClass('hover');
},function(){
$(this).removeClass('hover');
});
};
The corresponding CSS code is as -
tr.hover{
background-color:#E7ECB8;
color:#990000;
}
You will move your mouse on the table, it will change the row color as well as rwo text color and when you click on particular row, it will enable the row by selecting radio button..
If this answer is helpful for you then please like it for answer, so that others can use it for reference.... Thanks and best of luck

Categories