How to let user hide rows from a html table - javascript

I have a table which gets dynamically populated by the results of a search query:
echo '<table class="table">';
if ($num==0) echo "<tr><td>Sorry, no items found.</td></tr>";
else {
echo '<tr> <th>Nr.</th> <th>Name</th>';
echo '<th>Description</th> <th>Image</th>';
$lf = 1;
while ($dsatz = mysql_fetch_assoc($res))
{
echo '<tr>';
echo "<td>$lf</td>";
echo '<td>' . $dsatz["name"] . '</td>';
echo '<td>' . $dsatz["description"] . '</td>';
echo '<td><img src="' . $dsatz['image'] . '" style="height:100px; width:auto" /></td>';
echo '</tr>';
$lf = $lf + 1;
}
}
echo '</table>';
The result is a table of items. Now what I would like to do is give the user the possibility to hide any row by a single click or, if not possible, by checking boxes and hiting a second Hide(delete) button at the and of the table. The rows must not be deleted from the database only hidden from view.
Any ideas how I could do this?
Thx
Seb
///////////////////////////// EDIT ////////////////////////////////////////////
Thx for the Input!
Here is what worked for me:
In table:
echo "<td><input type='checkbox' name='hide_cand' style='float:right' id='hide_cand' onclick=' return hideRow(this)'/></td>";
script:
function hideRow(checkbox)
{
if(confirm('This action can not be undone, are you sure you want to delete this item from the list?'))
{
checkbox.parentNode.parentNode.style.display = "none";
return true;
}
return false;
}
Thx for your help!

Basically, you want something like this:
$('.table').on('click','tr',function(){
$(this).hide();
});
If you wish to add checkbox inside each row:
$('.table').on('change','tr :checkbox',function(){
$(this).closest('tr').hide(); //no need here to check for checkbox state
});

Think the far most easy would be :
$('.table tr').click(function() {
$(this).hide();
});

Try something like this
$("#tableID").delegate("td", "click", function() {
$(this).closest("tr").hide();
});

Related

Change style of a single element in a loop

This might confuse but a serious question.
I'm getting table rows from a loop using php and I'm displaying those table inside a table tag using ajax.
Here for the each row there is an id called productTableRow.
So I want to do is, in this table when I click a specific row, I want to change that clicked row's background color.Just only that row and to take the value of the clicked row attribute called product-id and show it in another hidden input
$(document).on('click', function(e){
if($(e.target).is('#productTableRow')){
var productId = $(e.target).attr('productId');
if(productId == productId){
$(e.target).css('background-color','#128C7E');
} else {
$('.trProductTable').css('background-color', 'transparent');
}
}
});
This is my php code which generating the Table rows,
foreach ($products as $product) {
$responseData .= "<tr id='productTableRow' productId='" . $product->id . "'>";
$responseData .= "<td>" . $product->id . "</td>";
$responseData .= "<td>" . $product->product_name . "</td>";
$responseData .= "<td>" . $product->product_barcode . "</td>";
if ($product->group_id == 0) {
$responseData .= "<td>None</td>";
} else {
$responseData .= "<td>" . $product->group_name . "</td>";
}
$responseData .= "<td>" . $product->product_cost . "</td>";
$responseData .= "<td>" . $product->product_selling . "</td>";
if ($product->product_type == 0) {
$responseData .= "<td>Liquid</td>";
} else if ($product->product_type == 1) {
$responseData .= "<td>Weight</td>";
} else if ($product->product_type == 2) {
$responseData .= "<td>Quantity</td>";
}
$responseData .= "<td>" . $product->created_at . "</td>";
Tried this code but doesn't work, really appreciate your help.
After changing the id to a class, I would try this
$('tr.productTableRow').click(function(){
var productId = $(this).attr('productId');
if(productId === productId){ // Always true
$(this).css('background-color','#128C7E');
} else {
// Do something when false ???
}
});
Edit Note: this code must be run after the table is added to the html, if you need to run it before, put the code inside a $(document).ready(function(){/*code */ });
Edit: Answer based on the comments
$(document).on('click', '.productTableRow', function(){
if(oldObject) {
$(oldObject).css('background-color', 'transparent');
}
var productId = $(this).attr('productId');
if(productId === productId){ // Always true
$(this).css('background-color','#128C7E');
}
oldObject = this;
});
First of all, id has to be specific to one element. Jquery is configured as this. Then you can use $(this).parent(‘tr’)
To get the parent row in the click event that can be to the entire class.
I arrived at my own answer,
$(document).on('click', '.groups-product-sidebar', (e)=>{
//Getting the clicked group attributes
var groupId = $(e.target).attr('groupId');
$('.groups-product-sidebar').parent().css('background-color','transparent');
$(e.target).parent().css('background-color','#128C7E');
});

Table does not disappear on AJAX call

I am trying to remove to this table on successful delete from an AJAX to PHP call.
Below is the function ,
list.php
<script type="text/javascript">
function massDelete()
{
if (!confirm("Are you sure"))
{
return false;
}
else
{
var selecedids = $("#selectedids").val();
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("success").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_delete.php?massDelete=" + selectedids.value, true);
xhttp.send();
}
}
return false;
}
</script>
the above code successfully gives me the selected ID for deletion
on this PHP side which is on another File
ajax_delete.php
<?php
if (!empty($_REQUEST['massDelete'])) {
$selectId = $_REQUEST['massDelete'];
$finalId = ltrim($selectId, ",");
$sql = mysql_query("delete from contact_form where contactUser_id in ($finalId)", $con);
if ($sql) {
// echo '<script>';
//echo 'var parent = document.getElementById("fullTable")';
//echo 'element.remove(parent)';
//echo '</script>';
echo "sucess deleted";
} else {
echo "Please select a Contact to delete";
}
}
?>
The response does give me the successful message, but somewhere I want to disappear the below HTML table in response
list.php
<?php
echo '<table id="fullTable">';
echo "<tr><td> ";
echo '<input type="checkbox" name="checkAll" id="checkAll"/></td>';
echo '<td colspan="8" align="right">';
echo '<button type="submit" onClick="return massDelete()" name="delete" class="deleteall" id="deleted">Delete All</button></td>';
echo "</tr>
<tr>
<th></th>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>EMAIL</th>
<th>PHONE</th>
<th>FAX</th>
<th></th>
<th></th>
<th></th>
</tr>";
while ($row = mysql_fetch_array($results)) {
echo '<div id="checkboxlist">';
echo '<tr class="show">';
echo '<td><input name="checkbox[]" type="checkbox" class="checkbox1" value="' . $row['contactUser_id'] . '" id="Checkbox1"></td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['phone'] . '</th>';
echo '<td>' . $row['fax'] . '</td>';
echo '<td>Edit</td>';
echo '<td><a class="delete" href="#" id="' . $row['contactUser_id'] . '">Delete</a></td>';
echo '<td>View</td>';
echo '</div>';
}
} else {
echo '<td colspan="9"><h1>No contacts found.</td></h1>';
}
?>
I am confused to what should I do so that if one row is deleted than only that row disappears,
but if all the checkboxes are selected for deletion, than on sucess, tha whole table should disappear..
So it sounds like the php successfully deletes it since when you refresh the page the correct data shows up.
But if the page has to be refreshed for it to show up properly, you need to make sure you are returning the correct information, and parsing it correctly. Just console.log() the response xhttp.responseText, and see if the correct data is returned, and then double check you are parsing it correctly (changing the dom appropriately).
You don't need to refresh your page to show it's correct. You need to use javascript to remove the row on success. Here's the basics:
var deletedRow = $('#fullTable');
$.post('script.php', {data:data}, function(){
if(data == "success"){
deletedRow.remove(); //This will remove the row from the view
}
});
Ajax can return a call and you give a statement that shows if success, you have to have javascript actually delete it. Yes, we know it's removed from the database, so you can successfully remove the view from the page.
UPDATE This is using jQuery, not pure javascript. But it's only an example to show that you need to delete the element using javascript and it won't just disappear because it's not in your database anymore.
Finally after referring to this remove any element using Jquery
I found the solution, and I also changed the AJAX function code which is mentioned below,
function massDelete()
{
var element = $(this);
var selecedids = $("#selectedids").val();
var info = 'massDelete=' + selectedids.value;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "ajax_delete.php",
data: info,
success: function(){
}
});
$this.parent("#fullTable").load("list.php");
}
return false;
}
the $this.parent("#fullTable").load("list.php"); statement reloaded that table hence reflecting only those information which are present in the database.

Class Based Click Event Irresponsive after 10 Rows - Datatables

I have a Table as such:
<?php
foreach($cars->result() as $car){
echo '<tr>';
echo '<td id="'.$car->car_id.'_id">'.$car->car_id.'</td>';
echo '<td id="'.$car->car_id.'_nm">'.$car->car_name.'</td>';
echo '<td id="'.$car->car_id.'_ph">'.$car->rate_per_hr.'</td>';
echo '<td id="'.$car->car_id.'_pk">'.$car->rate_per_km.'</td>';
echo '<td id="'.$car->car_id.'_mh">'.$car->min_hrs.'</td>';
echo '<td><span class="glyphicon glyphicon-edit"></span></td>';
echo '<td><span class="glyphicon glyphicon-remove"></span></td>';
echo '</tr>';
}
?>
I am using DataTables to display the datagrid.
Now, I have an Edit Button for each row which bears the same class but seperate IDs as the code above demonstrates. Based on the click on the class I am extracting the ID and then doing some ajax operations.
Code Edited for simplicity
$('.car_edit').click(function(e){
e.preventDefault();
var id= $(this).attr('id');
var len = id.length;
var row_id = id.substr(3 , len);
console.log(row_id);
});
Now, this is working perfectly fine for the first 10 rows (Default Display of the DataTables) after which the click event is not triggered.
I am bending my mind over this. Please help me point out my mistake.
Thank you.
Try jquery on():
$(function(){
$(document).on('click','.car_edit',function(event){
event.preventDefault();
var id= $(this).attr('id');
var len = id.length;
var row_id = id.substr(3 , len);
console.log(row_id);
});
});
According to docs: Attach an event handler function for one or more events to the selected elements https://api.jquery.com/on/

Give row color after onClick row and make request other page and stay color changed

I need Give row color after onClick row and make request other page and stay color changed
Notes: Currentaly change row color and disable color changed after refres page
<script type="text/javascript">
var id = $row['id'];
function myPopup(id) {
if (id) {
location.href = "address.php?id="+id;
}
}
</script>
<script>
$(document).ready(function () {
$('#imagetable tr').click(function () {
$(this).css('background-color', 'Green');
});
});
</script>
<?php
$resualt=mssql_query("SELECT * FROM Address ") ;
echo "<table border='1' class='imagetable'
id='imagetable' width='50%'>\n";
echo '<tr>';
echo '<th>ID</th>'.'<th>User ID</th>'.'<th>Street</th>'.'<th>Quarter</th>'.'<th>Mobile Number</th>'.'<th>Email</th>'.'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>';
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])'>\n"."<td >{$row['id']}</td>\n"."<td> {$row['user_id']}</td>\n"."<td>{$row['street']}</td>\n"."<td>{$row['quarter']}</td>\n"."<td>{$row['Phone_number']}</td>\n"."<td> {$row['email']}</td>\n"."<td>{$row['from_date']}</td>\n"."<td>{$row['to_date']}</td>\n"."<td>{$row['other_info']}</td>\n".'</tr>'."\n";
}
echo "</table>\n";
?>
Any help?
In your PHP check if the given ID matches the ID in the while loop. When that matches, add a style parameter or a CSS class depending on your situation.
Examples:
// Your code leading up to the while loop is here ...
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])" . ($_GET['id'] == $row[id] ? "style='background-color: green'":"") . "'>\n".
"<td >{$row['id']}</td>\n".
// The rest of the code in your loop continues here ...
It is not the most beautiful or safe code, but it suits the code you already have i think.

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Categories

Resources