jQuery drag & drop table rows sort not working - javascript

I wanted to make a script to order some rows from a database with drag & drop. The rows are displayed in a table, and I drag and drop rows to reorder them. Each tr have the row id from database. When I drag and drop a row, jquery serialize the table content and sends it to php to save rows position.
What could be the problem that rows position are not saved in db?
Table with rows:
$select_categories = mysqli_query($db_connect, "SELECT `id`, `title` FROM `categories` ORDER BY `category_order` ASC") or die(mysqli_error());
if(mysqli_num_rows($select_categories) != 0)
{
echo '<table cellpadding="0" cellspacing="0" class="manage_content" id="sort_rows" align="center">';
while($category = mysqli_fetch_assoc($select_categories))
{
echo '
<tr id="row-'.$category['id'].'">
<td width="700">'.$category['title'].'</td>
<td>Delete</td>
</tr>
';
}
echo '</table>';
}
jQuery
$("#sort_rows tbody").sortable({
cursor: 'move',
delay: 180,
update: function()
{
var rowsOrder = $(this).sortable("serialize");
$.post("ajax_actions.php", { action:'change_rows_order', table:'categories', order:'category_order', rows_order:rowsOrder } );
}
}).disableSelection();
AJAX
if(isset($_POST['action']) && $_POST['action'] == 'change_rows_order')
{
$order_no = 1;
foreach($_POST['rows_order'] as $row_id)
{
$update_order = mysqli_query($db_connect, "UPDATE `".clear_tags($_POST['table'])."` SET `".clear_tags($_POST['order'])."` = '".$order_no."' WHERE `id` = '".$row_id."'") or die(mysqli_error());
$order_no++;
}
}
HTML
<table cellpadding="0" cellspacing="0" class="manage_content" id="sort_rows" align="center">
<tr id="row-10">
<td width="700">Editorial</td>
<td>Delete</td>
</tr>
<tr id="row-11">
<td width="700">Fashion</td>
<td>Delete</td>
</tr>
<tr id="row-12">
<td width="700">Street Style</td>
<td>Delete</td>
</tr>
<tr id="row-13">
<td width="700">Portraits</td>
<td>Delete</td>
</tr>
<tr id="row-14">
<td width="700">Clothing</td>
<td>Delete</td>
</tr>
</table>

I solved the problem. I followed the tutorial here: http://www.webresourcesdepot.com/dynamic-dragn-drop-with-jquery-and-php/

Related

How to highlight table rows by hover over another div?

i have two tables
<table id='standings'>
<tr id='tableTeam1'>
<td>Team1</td>
</tr>
<tr id='tableTeam2'>
<td>Team2</td>
</tr>
<tr id='tableTeam3'>
<td>Team3</td>
</tr>
</table>
<table id='matches'>
<tr id='match1'>
<td id='matchTeam1>Team1</TD>
<td class='score'> 22-31</td>
<td id='matchTeam3>Team3</td>
</tr>
</table>
My goal is to hover over the row with id 'match1' from the second table and have the rows with id 'tableTeam1' and 'tableTeam3' highlighted
1.)
how is this possible by js/css?
2.) How can it be done by using a php database request when
"Select tableTeam1,tableTeam2 from matches where id='match1'"
Thank you so much in advance
Try this:
$('#match1')
.mouseenter(function() {
$('#tableTeam1').addClass('highlighted');
})
.mouseleave(function() {
$('#tableTeam1').removeClass('highlighted');
})
You also need to add some CSS there, like this one:
.highlighted { background-color: red;}
I don't know your data structure but it should be something like that, I think:
...
<tr id="<?php echo $data['column_name']; ?>" <?php echo ($data['column_name'] === 'match1')? 'class="highlighted"' : ''; ?>>
...
Put your team numbers in a data attribute in rows of the matches then it is fairly simple to parse them to match the elements in the other table and toggle a class on them
$('#matches .match-row').hover(function() {
const teams = $(this).data('teams');
teams.forEach(num => $('#tableTeam' + num).toggleClass('active'))
})
tr.active {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='standings' border=1>
<tr id='tableTeam1'>
<td>Team1</td>
</tr>
<tr id='tableTeam2'>
<td>Team2</td>
</tr>
<tr id='tableTeam3'>
<td>Team3</td>
</tr>
</table>
<table id='matches' border=1>
<tr class="match-row" data-teams="[1,3]">
<td>Team1</td>
<td class='score'> 22-31</td>
<td>Team3</td>
</tr>
<tr class="match-row" data-teams="[2,3]">
<td>Team2</td>
<td class='score'> 55-1 Blowout!</td>
<td>Team3</td>
</tr>
</table>

Calculate sum of input values in for loop [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 8 months ago.
I have a table with 4 columns. The first one is the name of a product, the second has the price per item, the third column has an input field where you can choose how many items you want, and the last column calculates the price per item * number of items.
This calculation works, but I also want to calculate all of these into a total at the bottom of the table.
I know very little javascript, so I'm not sure if I'm using the correct functions or methods.
The code consists of PHP, HTML and Javascript.
for ($i = 0; $i < $num_rows; $i++){
echo '<tr><td>' . $row[$i][0] . '';
echo '<td id="stkPris_' . $i . '">' . $row[$i][1] . '</td>';
echo '<td><input type="text" id="antall_' . $i .'" name="antall" size="1" value="0" oninput="calculate(value, this.id)"></td>';
echo '<td><input type="text" id="pris_' . $i . '" name="pris" size="1" readonly></td></tr>';
}
echo '
<tr>
<td><strong>Sum</strong></td>
<td></td>
<td></td>
<td><strong><input type="text" id= "sum" name="sum" size="1" value="0" readonly><strong></td>
</tr>
</table>';
<script>
function calculate(value, elementId){
var i;
for (i = 0; i < ' . $num_rows . '; i++){
var stkPris = document.getElementById("stkPris_" + i);
var antall = document.getElementById("antall_" + i);
var pris = document.getElementById("pris_" + i);
var sum = document.getElementById("sum");
var delsummer = antall.value * stkPris.innerText;
if(elementId == "antall_" + i){
pris.value = delsummer;
}
sum.value += pris.value;
}
}
</script>
How it looks (image)
The total seem to be a string and not a number? I have tried putting the "price per item" into an input instead and use .value instead of .innerText. Didn't do anything.
Here is a simple way to calculate stock and price, read code comments to know more.
$(document).ready(function(){
var totalStock = 0;
var totalPrice = 0;
$(".stock").each(function(){
var s = parseInt($(this).text()); // to get the stock count
var p = parseFloat($(this).parent().find(".price").text()); // to get unit price of this stock
$(this).parent().find(".sumPrice").html(s*p); // calculate Stock x Price
totalStock += s; // calculate total Stocks
});
$(".price").each(function(){
var p = parseFloat($(this).text()); // to get unit price
totalPrice += p; // calculate total prices
});
$(".stockTotal").html(totalStock); // show total stock count
$(".priceTotal").html(totalPrice); // show total prices
$(".generalTotal").html(totalStock * totalPrice); // calculate all prices x all stock
});
table{
width:100%;
}
table th, table td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>Stock</th>
<th>Price</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>item name</td>
<td class="stock">25</td>
<td class="price">17</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>2</td>
<td>item name</td>
<td class="stock">1</td>
<td class="price">12.5</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>3</td>
<td>item name</td>
<td class="stock">6</td>
<td class="price">9.75</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>4</td>
<td>item name</td>
<td class="stock">0</td>
<td class="price">20</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>5</td>
<td>item name</td>
<td class="stock">11</td>
<td class="price">15</td>
<td class="sumPrice">##</td>
<tr>
<tr>
<td>6</td>
<td>item name</td>
<td class="stock">3</td>
<td class="price">3.25</td>
<td class="sumPrice">##</td>
<tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td class="stockTotal">#stock total#</td>
<td class="priceTotal">#price total#</td>
<td class="generalTotal">#price total x stock total#</td>
</tr>
</tfoot>
</table>

datatable with child rows using mysql

In MySQL Database, I have two tables Abc and Pqr. In Abc table there's a unique ID, that ID is used in Pqr table as foreign key.
I want to show the parent element as Abc table data and child rows as Pqr table data with respect to Abc unique ID.
Here is my code:
$sqlGetParents="SELECT * from projectrera order by project_id";
$resultGetParents = $conn->query($sqlGetParents);
?>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Project Name</th>
<th>Builder Id</th>
<th>Location Id</th>
<th>Phase</th>
<th>Status</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($resultGetParents)) {
echo " <tr>
<td class='details-control'></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
} ?>
</table>
<div id="test">
<table id='example1'>
<?php
$sqlGetCatWithParent1="SELECT * from info";
$resultGetCatWithParent1 = $conn->query($sqlGetCatWithParent1);
while ($row3 = mysqli_fetch_array($resultGetCatWithParent1)) {
echo " <tr>
<td></td>
<td>".$row3[1]."</td>
<td>".$row3[2]."</td>
<td>".$row3[3]."</td>
</tr>";
}
?>
Why don't you use the JOIN or Subquery on your select statement? I think that would help you since you're using a relational schema on your tables.
Example:
$sqlGetParents =
SELECT abc.*, pqr.* from projectrera abc
LEFT JOIN info pqr on pqr.project_id = abc.project_id
order by project_id
In your HTML table, I suggest to use FOREACH instead of WHILE.
<?php foreach ($row->result() in $resultGetParents) {
echo "<tr>
<td class='details-control'></td>
<td>".<?php echo $row[1]."</td>
<td>".$row[1]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
echo "<tr>
<td></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
</tr>";
} ?>
You can change the $row number based on the results or use text to easily know which columns should be displayed on your table. (i.e $row['project_id'])

Refresh div after delete table row

I can successfully delete rows of my table and remove it from the table with jquery and ajax. On top of my table i have the number of rows displayed. How can i refresh the div (update_count) to show the decremented number after deleting ?
<div id="update_count"><?=$num_count?> data</i></div>
<table class="table">
<tr>
<th style="width:1px"><strong>Date</strong></th>
<th style="width:5px">Labo</th>
<th style="width:5px">Delete</th>
<tr>
<?php foreach($IndicacionesLab as $row)
{
?>
<tr>
<td><?=$row->insert_time;?></td>
<td><?=$row->laboratory;?></td>
<td> <a title="Eliminar laboratorio <?=$row->laboratory;?>" class="st deletelab" id="<?=$row->id_lab; ?>" style="background:rgb(223,0,0);cursor:pointer">Delete</a></td>
</tr>
<?php
}
?>
</table>
Js
$(".deletelab").click(function(){
if (confirm("Sure to delete ?"))
{
var el = this;
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'<?=base_url('admin/DeleteHistLab')?>',
data: {id : del_id},
success:function(response) {
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
}
})
For simplicity keep all the data rows in a <tbody>
<table id="my-table">
<thead>
<tr>
<th> heading 1 </th>
</tr>
</thead>
<tbody>
<tr>
<th> data 1 </th>
</tr>
</tbody>
</table>
Then after you remove the row get the length of all rows remaining
$('#update_count').text( $('#my-table tbody tr').length + ' Items')

Highlight table cell based on vertical and horizontal headers

I have a "football squares" game going, and I would like to highlight cells of the winners based on the top and side headers.
Now, I know they're not really headers but they serve the same purpose.
My table is located at this jfiddle: https://jsfiddle.net/8ybtntqg/
What I want to do is this:
Let's say the winner would be whoever is in the cell that lines up with TeamA - 2 and TeamZ - 9. That would be Mitch. I want to highlight Mitch's cell. How would I do this with Javascript or Jquery? I know how to do it if I was just looking for the word "Mitch", but I want to automatically do it, based on the numbers of TeamA and TeamZ.
I have this so far, but of course that only highlights the name but it's the only place I knew to start:
$('#table_id td').each(function() {
if ($(this).text() == 'Mitch') {
$(this).closest('td').css('background-color', '#f00');
}
});
You can get the index of the column and row using jQuery's filter() method.
That will give you direct access to the cell like so:
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
Snippet:
function highlight(teamA, teamZ) {
var col, row;
col = $('#table_id td').filter(function() { //return column of teamA
return $(this).html() === teamA.replace(' - ', '<br>');
}).index();
row = $('#table_id tr').filter(function() { ////return row of teamZ
return $(this).html().indexOf(teamZ.replace(' - ', '<br>')) > -1;
}).index();
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
}
highlight('TeamA - 2', 'TeamZ - 9');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="table_id">
<tr>
<td>Squares</td>
<td>TeamA<br>1</td>
<td>TeamA<br>2</td>
<td>TeamA<br>3</td>
<td>TeamA<br>4</td>
<td>TeamA<br>5</td>
<td>TeamA<br>6</td>
<td>TeamA<br>7</td>
<td>TeamA<br>8</td>
<td>TeamA<br>9</td>
<td>TeamA<br>0</td>
</tr>
<tr>
<td>TeamZ<br>3</td>
<td bgcolor="#89ff89">Mark</td>
<td bgcolor="#89ff89">John</td>
</tr>
<tr>
<td>TeamZ<br>5</td>
<td bgcolor="#89ff89">Mike</td>
<td bgcolor="#89ff89">Earl</td>
</tr>
<tr>
<td>TeamZ<br>8</td>
<td bgcolor="#89ff89">Morris</td>
<td bgcolor="#89ff89">Brice</td>
</tr>
<tr>
<td>TeamZ<br>7</td>
<td bgcolor="#89ff89">Taylor</td>
<td bgcolor="#89ff89">Evan</td>
</tr>
<tr>
<td>TeamZ<br>9</td>
<td bgcolor="#89ff89">Mandy</td>
<td bgcolor="#89ff89">Mitch</td>
</tr>
<tr>
<td>TeamZ<br>2</td>
<td bgcolor="#89ff89">Tony</td>
<td bgcolor="#89ff89">Jennifer</td>
</tr>
<tr>
<td>TeamZ<br>1</td>
<td bgcolor="#89ff89">Kristen</td>
<td bgcolor="#89ff89">Hector</td>
</tr>
<tr>
<td>TeamZ<br>4</td>
<td bgcolor="#89ff89">Gabby</td>
<td bgcolor="#89ff89">David</td>
</tr>
<tr>
<td>TeamZ<br>6</td>
<td bgcolor="#89ff89">George</td>
<td bgcolor="#89ff89">Steffanie</td>
</tr>
<tr>
<td>TeamZ<br>0</td>
<td bgcolor="#89ff89">Breck</td>
<td bgcolor="#89ff89">Terry</td>
</tr>
</table>
You can iterate over all the table elements to find the matching values, then use CSS selectors to highlight the matched field. Something like this will work:
winningAScore = 2;
winningZScore = 9;
//get top row
counter = 0;
$('#table_id tr:first-child td').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningAScore) {
posnX = counter;
}
counter++;
})
//get first column row
counter = 0;
$('#table_id tr td:first-child').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningZScore) {
posnY = counter;
}
counter++;
})
$('tr:eq('+posnY+') td:eq('+posnX+')').css('background-color', 'red');
You can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/8ybtntqg/1/
You can do index based detect and selection in jQuery like so: $('tr:eq(2) td:eq(1)').css('background-color', 'red');
Example: http://codepen.io/anon/pen/EPLNvB

Categories