Change style of a single element in a loop - javascript

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');
});

Related

Passing Parameters To PHP Table Hyperlink

I want the second and third columns of my php table to be a hyperlink to a different page for each row. I need to pass 3 parameters to the hyperlink
1) The value from the first column - empID listed in the table below
2) The value from $weekStart - selected from a input type="date" at top of page
3) The value from $weekEnd - selected from a input type="date" at top of page
I am trying this syntax, but it is not passing in the parameters and I am getting a page not found error. How should this syntax be altered so that it passes all 3 params and navigates to the appropriate page?
Week Start:<input type="date" name="weekStart">
Week End:<input type="date" name="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
?>
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td>'.$Row['DailySales'].''" . $res->DailySales . "</td>";
print "<td>'.$Row['SalesForWeek'].''" . $res->SalesForWeek . "</td>";
print "</tr>";
}
You didn't append the string well. Please try the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['SalesForWeek']."</a>" . $res->SalesForWeek . "</td>";
print "</tr>";
}
If it still shows not found page, then please check the file names.
Update: I hope you need to replace some variables in your loop as updated in the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->SalesForWeek."</a></td>";
print "</tr>";
}
Completely untested and I'm not 100% sure what the data in those links were supposed to be doing, but I think this should give you a solid starting point and you can tweak the HTML generation to get what you want.
I wouldn't bother trying to do it in PHP at all, pass the entire data set to JS and do it there.
Week Start:<input type="date" name="weekStart" id="weekStart">
Week End:<input type="date" name="weekEnd" id="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
// Create a JSON version of your data to pass to the script
$data = json_encode( $tsql );
?>
<!-- Create an empty table for your data-->
<table id="employee-table"></table>
<script>
$("#submitForm").on("click", function(e) {
// Stop the form from reloading the page
e.preventDefault();
// Set up your variables, you'll need to add ID's to the form inputs
var employees = <?php echo $data; ?>;
// See the employees data in your inspector console
console.log(employees);
var weekStart = $("#weekStart").val();
var weekEnd = $("#weekEnd").val();
// Generate the HTML for all the employees
var html = "";
for( var1=0; i<employees.length; i++ ) {
html += "<tr>";
html += "<td>" . employees[i].EmpID . "</td>";
html += "<td>" + employees[i].DailySales + "</td>";
html += "<td><a href='WeeklySales.php?param1='" + weekStart + "'&param2='" + weekEnd + "'&param3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>

Why doesn't 'onclick' work when html is sent through php?

There is a javascript in my page that loads a PHP script into a div every second. This PHP is supposed to run a SQL query that loads data from a database.
Here is an extract of the PHP
while($row = mysqli_fetch_array($result))
{
$starttime = $row['start_time'];
$module = $row['module'];
$item = $row['item'];
echo "<tr>";
echo "<td>" . $row['start_time'] . "</td>";
echo "<td>" . $row['module'] . "</td>";
echo "<td>" . $row['item'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['accepted'] . "</td>";
echo "<td>" . $row['end_time'] . "</td>";
echo "<td><button id='btnaccept' onclick='acceptBtn()'>ACCEPT</button></td>";
echo "</tr>";
}
And here is the Javascript
<script>
var auto_refresh = setInterval(
(function () {
$("#dataDisplay").load("updatedb.php"); //Load the content into the div
}), 1000);
</script>
As you can see, the last table data is a button that runs a Javascript function
<script>
function acceptBtn() {
window.alert("Accepted");
}
</script>
But unfortunately, clicking this button won't run the function. Any help would be appreciated
Try set listener:
echo "<td><button id='btnaccept'>ACCEPT</button></td>";
.
$(document).on('click', '#btnaccept', acceptBtn);
function acceptBtn(event) {
event.preventDefault();
window.alert("Accepted");
}

On table row click, alert box shows click value

i'm having problems where when i click the tablerow, nothing is being shown.
When I click lets say the row where customername= 'John', the name 'John' should appear on a alert box, but nothing happens.
This is my table click code.
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
And, here is my generating of table code.
if(!empty($_GET['q'])){
$q = $_GET['q'];
$query="select * from customer where customername like '$q%'";
$result = mysqli_query($dbconn,$query);
echo "<div id='parentElementIdHere'>";
echo "<table id='test' border=3>
<tr>
<th>Customername</th>
<th>nric</th>
<th>email</th>
<th>mobileno</th>
<th>telephoneno</th>
<th>address</th>
<th>postalcode</th>
<th>datejoined</th>
<th>points</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['customername'] . "</td>";
echo "<td>" . $row['nric'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['mobileno'] . "</td>";
echo "<td>" . $row['telephoneno'] . "</td>";
echo "<td>" . $row['occupation'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['postalcode'] . "</td>";
echo "<td>" . $row['datejoined'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
Could the problem be because my table generated is constantly changing because of ajax?
To get name value for click on any value of the row
$("tr").click(function() {
var str = this.innerText;
var i = str.split('').indexOf(" ");
alert(str.slice(0, i));
})
http://codepen.io/nagasai/pen/QENwgQ
to get table cell value on click
$("td").click(function(){
alert(this.innerText);
})
codepen URL for reference- http://codepen.io/nagasai/pen/jrqEBz
Hope this is helpful for you
There are two main problems with your code:
Your selector '#test tr #name' says to select all elements with id="name" that are descendants of tr elements, but it is actually your tr elements that all have that id. (And speaking of them all having that same id, duplicate ids is invalid HTML.)
Calling .click() binds a click handler to elements that exist at that moment. Which means that when your table changes due to an Ajax call your click handler would not work for the newly loaded/created elements even if you fixed the selector.
The solution to both problems is to use a delegated event handler, which you bind to the table element's parent (or to the nearest ancestor element that does not get overwritten by the Ajax call):
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
});
When a click occurs on any descendant element of the parent element, jQuery will check if the specific clicked element matches the selector that is the second argument to the .on() method, and if so it will call your function with this set to the matching element. Because the matching element is a tr element, you would then use .find("td").first() to get that row's name td.
Demo: https://jsfiddle.net/269Lt9hm/
I managed to solve it. I tested with a non ajax generated sql table and did it. Then i brought over the javascript code over to this file and tried it out. This is the code i used.
$(document).ready(function(){
}).on('click','.test tr',function(){
var id = $(this).attr('value');
alert(id);
});
Thanks to all who helped me i appreciate it!

Sanitize strings to avoid special characters break javascript generated by php

I have a php 'search' script that looks for the requested data in a MySQL database and prints a table. Each row of this table can be modified or deleted by clicking on an icon. When you click on one of these icons a javascript function that shows a display is called.
This is the piece of code:
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Sanitize output
$user = htmlentities($row[0]);
$name = htmlentities($row[1]);
$surnames = htmlentities($row[2]);
$email = htmlentities($row[3]);
$role = htmlentities($row[4]);
$access = htmlentities($row[5]);
$center = htmlentities($row[6]);
$message .= "<tr>
<td>" . $user . "</td>" .
"<td>" . $name . "</td>" .
"<td>" . $surnames . "</td>" .
"<td>" . $email . "</td>" .
"<td>" . $role . "</td>" .
"<td>" . $access . "</td>" .
"<td>" . $center . "</td>" .
"<td>" .
"<input type='image' src='../resources/edit.png' id='edit_" . $user . "' class='edit' onclick=edit_user(\"$user\",\"$name\",\"$surnames\",'$email','$role','$access',\"$center\",'$id') title='Editar'></button>" .
"</td>" .
"<td>" .
"<input type='image' src='../resources/delete.png' id='delete_" . $user . "' class='delete' onclick=delete_user(\"$user\",'$role') title='Eliminar'></button>" .
"</td>
</tr>";
}
This is just part of the table I generate. After all this, I encode the table with json_encode and echo it. The echo is captured by an ajax function that decodes it (JSON.parse) and puts it into a div.
The table is correctly rendered and everything works fine with normal characters, but I have detected I can have some problems if I have quotes, slashes and another meaningfull characters. The strings are showed correctly in the table, so there is no problem with php, but the generated javascript doesn't work with some strings.
For example, if I introduce:
</b>5'"
or:
<b>5'6"</b><br><div
as users, when I click on edit or delete icon I get some errors in javascript console:
Uncaught SyntaxError: Invalid regular expression: missing /
home.php:1 Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: missing ) after argument list
Uncaught SyntaxError: Unexpected token ILLEGAL
I have tried with several combination of addslash, replace, htmlentites, htmlspecialchars... but I can't get the right one.
What's the right way to work with this in order to avoid any problem?
Thank you.
EDIT:
I have probed this and it seems to work:
In php I use this function:
function javascript_escape($str) {
$new_str = '';
$str_len = strlen($str);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . dechex(ord(substr($str, $i, 1)));
}
return $new_str;
}
and then I use something like
$('<textarea />').html(user).text()
in javascript to decode the string.
Is this safe against XSS attacks?
First, create an HTML-safe JSON string of the array and modify your code to use a data attribute like so:
while ($row = mysqli_fetch_row($result)) {
// Define $id
$id = $row[7];
// Sanitize output
$user = htmlentities($row[0]);
$name = htmlentities($row[1]);
$surnames = htmlentities($row[2]);
$email = htmlentities($row[3]);
$role = htmlentities($row[4]);
$access = htmlentities($row[5]);
$center = htmlentities($row[6]);
$json_str_edit = htmlentities(json_encode(array($row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $id)));
$json_str_delete = htmlentities(json_encode(array($row[0], $row[4])));
$message .= "<tr>
<td>" . $user . "</td>" .
"<td>" . $name . "</td>" .
"<td>" . $surnames . "</td>" .
"<td>" . $email . "</td>" .
"<td>" . $role . "</td>" .
"<td>" . $access . "</td>" .
"<td>" . $center . "</td>" .
"<td>" .
"<input type=\"image\" src=\"../resources/edit.png\" id=\"edit_$user\" class=\"edit\" data-user=\"$json_str_edit\" title=\"Editar\"></button>" .
"</td>" .
"<td>" .
"<input type=\"image\" src=\"../resources/delete.png\" id=\"delete_$user\" class=\"delete\" data-user=\"$json_str_delete\" title=\"Eliminar\"></button>" .
"</td>
</tr>";
}
Then create an event listener to catch associated click events in JS like this:
function edit_user(user, name, surnames, email, role, access, center, id) {
// `this` will refer to the html element involved in the event
}
function delete_user(user, role) {
// `this` will refer to the html element involved in the event
}
document.addEventListener('click', function(event) {
if(event.target.hasAttribute('data-user')) {
switch(event.target.className) {
case 'edit':
edit_user.apply(event.target, JSON.parse(event.target.dataset.user));
break;
case 'delete':
delete_user.apply(event.target, JSON.parse(event.target.dataset.user));
break;
}
}
}, false);
Alternatively from the addEventListener method, you can simply add this onclick event listener directly to the element like so (I really don't think it matters in this case):
onclick="edit_user.apply(this, JSON.parse(this.dataset.user))"
FYI It's more common practice to use single quotes in scripts to avoid having to escape the double quote characters. Makes things both cleaner and more standardized.

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