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!
Related
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');
});
I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>
For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.
Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered
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."¶m2=".$weekEnd."¶m3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."¶m2=".$weekEnd."¶m3=".$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."¶m2=".$weekEnd."¶m3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."¶m2=".$weekEnd."¶m3=".$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 + "'¶m2='" + weekEnd + "'¶m3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>
I'm using a Dialog Widget for generate a popup with this code in my index.php:
<button class="btn btn btn-info openObs">Deixar observação</button>
<div id="dialog" title="Dialog Title">I'm a dialog</div>
and
$("#dialog").dialog({ autoOpen: false });
$(".openObs").click(function() {
$("#dialog").dialog("open");
});
so far no problem, but i have a ajax code that generate for me this buttons in a table in other archive and echoes the result back in my index.php in a result div:
$return .= "$tabela";
while($row = mysqli_fetch_assoc($query)){
$data = str_replace('-', '/', $row['consulta_data']);
$data = date('d/m/Y', strtotime($data));
$return .= "<tr>";
$return .= "<td>" .$row['consulta_idConsulta']."</td>";
$id = $row['documento_id'];
$return .= "<td>" .$data. "</td>";
$return .= "<td>" .$row['consulta_hora']. "</td>";
$return .= "<td>" .$row['consulta_desc']. "</td>";
$return .= "<td>" .$row['profissional_nome']. "</td>";
$return .= "<td>" . "<button class=\"btn btn btn-info openObs\">Deixar observação</button></td>";
$return .= "</tr>";
}
echo $return .=" </tbody>
</table>";
The problem is, when i click on the button generated by ajax nothing happens but if I put a button manually like up there works normal.
The issue is that the button is generated. To avoid this, you need to use on()
http://api.jquery.com/on/
$(body).on('click', '.openObs', function(){
});
Here is the js.fiddle for you. You can test it by enabling and disable individual function.
Make sure that the $(body) is not an element that is appended on later. So it can be $('.container'), as long as it is not javascript generated.
The problem in your case is that when you are binding the click function for dialog, the button you are creating with ajax is not present in the DOM yet , hence no binding will be done on the buttons created by ajax after your binding. To achieve this functionality, a simple way is to bind the same function again after you created the button with ajax. This will solve the issue.
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!