onmouseover showing same data over all rows in table - php

im having trouble getting a popup using javascript to show table data onmouseover when mousing over images returned in a table from the DB, now the problem i have isnt with actualy getting the onmouseover working (a previous question solved that) but getting the data displayed onmouseover the change for each image moused over.
the query's im using works fine and and display the correct data but on the onmouseover only ever shows the data which should only show for the first row in the table, the 2nd and subsequent rows should show different data as the query calls (which works, just doesnt show onmouseover)
keep in mind this page is included in my index.php which has all my .js and .css calls
page code:
<table border='0' cellpadding='0' cellspacing='0' class="center2">
<tr>
<td width='60'><img src="images/box_tl.png"></td>
<td style="background: url(images/box_tm.png)" align="center"><img src="images/news.png"></td>
<td width='25'><img src="images/box_tr.png"></td>
</tr>
<tr>
<td style="background: url(images/box_ml.png)"><h2>.</h2></td>
<td style="background: url(images/box_mm.png)">
<?php
include 'connect.php';
$query = mysql_query("SELECT * FROM tbl_img") or die(mysql_error());;
echo "<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Mob Name</th> <th>Id</th> <th>Health</th> <th>Body</th> <th>Effects</th> <th>Spawn</th></tr></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query )) {
$mob_id = $row['mob_id'];
$mob = $row['mob'];
$body = $row['body'];
$mob_name = $row['mob_name'];
$health = $row['health'];
$level = $row['level'];
// Print out the contents of each row into a table
echo "<tr><td>";
echo "<img src='/testarea/include/mobs/$mob' />";
echo "</td><td>";
echo $mob_name;
echo "</td><td>";
echo $level;
echo "</td><td>";
echo $health;
echo "</td><td>";
echo "
<a onmouseover='ShowPop()' href=''><img src='/testarea/include/mobs/dead/$body' /></a>
";
echo "
<div id='hidden-table' style='display:none;'>
<table border='0' cellpadding='0' cellspacing='0' class='center3'>
<tr>
<td width='14'><img src='images/info_tl.png'></td>
<td style='background: url(images/info_tm.png)' align='center'></td>
<td width='14'><img src='images/info_tr.png'></td>
</tr>
<tr>
<td style='background: url(images/info_ml.png)'><h2>.</h2></td>
<td style='background: url(images/info_mm.png)'>
";
$query2 = mysql_query("SELECT * FROM tbl_drop WHERE mob_name='$mob_name'") or die(mysql_error());
echo "<table border='0' cellpadding='1' cellspacing='1' width='250' id='2' class='tablesorter'><thead>";
echo "<tr> <th> </th> <th>Item Name</th> <th>Qty</th></thead><tbody>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $query2 )) {
$id = $row['id'];
$item_img = $row['item_img'];
$qty = $row['qty'];
$item_name = $row['item_name'];
// Print out the contents of each row into a table
echo "<tr><td width='50'>";
echo "<img src='/testarea/item/$item_img' />";
echo "</td><td width='150'>";
echo $item_name;
echo "</td><td width='50'>";
echo $qty;
echo "</td></tr>";
}
echo "</tbody></table>";
echo "
</td>
<td style='background: url(images/info_mr.png)'><h2>.</h2></td>
</tr>
<tr>
<td width='14'><img src='images/info_bl.png'></td>
<td style='background: url(images/info_bm.png)' align='center'><h2>.</h2></td>
<td width='14'><img src='images/info_br.png'></td>
</tr>
</table>
</div>"
;
echo "</td><td>";
echo "test";
echo "</td><td>";
echo "test";
echo "</td></tr>";
}
echo "</tbody></table>";
?>
</td>
<td style="background: url(images/box_mr.png)"><h2>.</h2></td>
</tr>
<tr>
<td width='60'><img src="images/box_bl.png"></td>
<td style="background: url(images/box_bm.png)" align="center"><h2>.</h2></td>
<td width='25'><img src="images/box_br.png"></td>
</tr>
</table>
</html>
popup.js code:
// create the popup box - remember to give it some width in your styling
document.write('<div id="pup" style="position:abolute; display:none; z-index:200;"></div>');
var minMargin = 15; // set how much minimal space there should be (in pixels)
// between the popup and everything else (borders, mouse)
var ready = false; // we are ready when the mouse event is set up
var default_width = 200; // will be set to width from css in document.ready
function ShowPop()
{
popup($('#hidden-table').html(), 400);
}
/* Prepare popup and define the mouseover callback */
jQuery(document).ready(function(){
$('#pup').hide();
css_width = $('#pup').width();
if (css_width != 0) default_width = css_width;
// set dynamic coords when the mouse moves
$(document).mousemove(function(e){
var x,y;
x = $(document).scrollLeft() + e.clientX;
y = $(document).scrollTop() + e.clientY;
x += 10; // important: if the popup is where the mouse is, the hoverOver/hoverOut events flicker
var x_y = nudge(x,y); // avoids edge overflow
// remember: the popup is still hidden
$('#pup').css('top', x_y[1] + 'px');
$('#pup').css('left', x_y[0] + 'px');
});
ready = true;
});
/*
The actual callback:
Write message, show popup w/ custom width if necessary,
make sure it disappears on mouseout
*/
function popup(msg, width)
{
if (ready) {
// use default width if not customized here
if (typeof width === "undefined"){
width = default_width;
}
// write content and display
$('#pup').html(msg).width(width).show();
// make sure popup goes away on mouse out
// the event obj needs to be gotten from the virtual
// caller, since we use onmouseover='popup(msg)'
var t = getTarget(arguments.callee.caller.arguments[0]);
$(t).unbind('mouseout').bind('mouseout',
function(e){
$('#pup').hide().width(default_width);
}
);
}
}
/* Avoid edge overflow */
function nudge(x,y)
{
var win = $(window);
// When the mouse is too far on the right, put window to the left
var xtreme = $(document).scrollLeft() + win.width() - $('#pup').width() - minMargin;
if(x > xtreme) {
x -= $('#pup').width() + 2 * minMargin;
}
x = max(x, 0);
// When the mouse is too far down, move window up
if((y + $('#pup').height()) > (win.height() + $(document).scrollTop())) {
y -= $('#pup').height() + minMargin;
}
return [ x, y ];
}
/* custom max */
function max(a,b){
if (a>b) return a;
else return b;
}
/*
Get the target (element) of an event.
Inspired by quirksmode
*/
function getTarget(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
}

All of the hidden tables have the same id, but IDs have to be unique.
provide the link as argument to ShowPop()
<a onmouseover='ShowPop(this)' ....>
then you'll be able to access the intended target inside ShowPop():
function ShowPop(o)
{
popup($(o).next('div').html(), 400);
}
Edit:
Regarding to the comment:
Currently I think the popup will not disapear onmouseout in any browser(except IE), because you didn't provide an argument to ShowPop() , what in other browsers is needed to return anything from getTarget, because they didn't know window.event.
Change this line:
var t = getTarget(arguments.callee.caller.arguments[0]);
to
var t = arguments.callee.caller.arguments[0];
...because when you take on my suggestion the link is already provided as argument to ShowPup(), there is no need to call getTarget() .

Related

Colspan from table doesn't work correctly

I have an HTML table, where if you click on the “<?php echo $row["title"]; ?>“, for each row, it will display the exercise text corresponding to that title.
This is working fine, it toggles correctly but I don’t know why the doesn’t work. The title only displays in one of the columns, but I would like to display on the 3 of them. Below I post a picture with what I get.
Can you help me solve this?
This is my code:
<tr>
<td><?php echo $num_ex; ?></td>
<!---Click Toggle Exercise-->
<td><a onclick="myFunction(<?php echo $row["exercise_id"] ?>)" role="button" class="btn" target="_blank" ><?php echo $row["title"]; ?></a>
</td>
<td><?php echo $row["difficulty"]; ?></td>
</tr>
<!--- Toggle --->
<tr id="toggle<?php echo $row["exercise_id"] ?>" style="display:none">
<td colspan="3"> <!---THIS COLSPAN IS NOT WORKING-->
<?php
$sql = "SELECT * FROM exercises WHERE exercise_id='".$row["exercise_id"]."'";
$result_ej = $conn->query($sql); /*Check connection*/
$row_ej = $result_ej->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
</td>
</tr><!---Finish Toggle --->
This is my script:
<script>
function myFunction(ejer_id) {
var x = document.getElementById("toggle" + ejer_id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Since you are changing the display of a <tr> you need to set it properly when you need to show it or else it does not obey table structure rules.
The issue is:
x.style.display = "block";
It should be:
x.style.display = "table-row";
Or, better yet just unset it if you don't want to keep track of the "correct" value:
x.style.display = "";
disclaimer: I do not know if all browsers will properly support this third option.
See https://stackoverflow.com/a/7971565/2191572 for other options.
You can also use:
x.style.display = "initial";
but it may not work in all browsers such as IE 11 and earlier per https://developer.mozilla.org/en-US/docs/Web/CSS/initial#Browser_compatibility

Displaying a progress bar in php file

I have a php file which selects a large amount of data from mutiple sql table. Naturally it takes a long time to complete the whole process. I want to display a progress bar which will express the progress of the script running. How to display a progress bar? The script below shows a portion of the php file.
<?php
//RIGHT(AdmitCode,1), PartCode, MID(AdmitCode,2,2), MID(AdmitCode,1,1) DESC, RollCode
$query = "SELECT * FROM students1 ORDER BY PartCode, AdmitCode, yearcode desc, RollCode";
$result = mysql_query($query);
// start a table tag in the HTML
echo "<table border='1' align='center' style='border-collapse:collapse' width='110%'>";
echo "<caption>
<h2>List of candidates for Three year Degree
(Honours/General) Programme Examination-".$bx1." (".$bx2.")
</h2>
</caption>";
//$row['index'] the index here is a field name
echo "<tr bgcolor=''>
<th> Sl. No </th>
<th>ID </th>
<th> Semester </th>
<th> Roll No </th>
<th> Registration No</th>
<th> Name </th>
<th> Honours </th>
<th> Elective-1 </th>
<th> Elective-2 </th>
<th> Elective-3 </th>
<th> MIL </th>
<th> Foundation </th>
<th> Soft studies </th>
<th> Syllabus </th>
</tr>";
$ty=0;
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$ty++;
if ($ty%2==0)
echo "<tr bgcolor='pink'>";
else
echo "<tr>";
echo "<td align='center'>$ty</td>
<td align='center'>" . $row['StudentID']." </td>
<td align='center'>" . $row['PartCode']."</td>
<td align='center'>" . $row['AdmitRollNo'] . "</td>
<td align='center'>" . $row['RegistrationNo']. "</td>
<td align='left'>" . $row['Name'] . "</td>
<td align='center'>" . $row['HonoursSubject'] . "</td>
<td align='center'>". $row['ElectiveSubject1'] . "</td>
<td align='center'>". $row['ElectiveSubject2'] . "</td>
<td align='center'>". $row['ElectiveSubject3'] . "</td>
<td align='center'>". $row['MIL'] . "</td>
<td align='center'>". $row['Foundation'] . "</td>
<td align='center'>". $row['SoftStudies'] . "</td>
<td align='center'>". $row['Syllabus'] . "</td>
</tr>";
}
echo "</table>"; //Close the table in HTML
Generally, to implement a good progress bar, you need a progress indicator from the layer which does the work, i.e. the mysql database. I am not aware, that mysql provides such a feature.
So you are stuck with estimating how long the operation will probably last (i.e. from past queries or derive it from the query parameters) and just implement a javascript progress bar (JQueryUI provides a good one), which is just time based.
Alternatively, you could just use a spinner to indicate, that you do not know how long this process really runs.
you can add div coantainer for the table and has id page and add css this show the loading image until page full load.
eg.
<div id="page">
<table>
</table>
</div>
css
<style>
#page {
display: none;
}
#loading {
display: block;
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100vw;
height: 100vh;
// background-image: url(loading_spinner.gif);
background-image:url("loading_spinner.gif");
background-repeat: no-repeat;
background-position: center;
}
</style>
<script>
$(window).load(function() {
$('#page').show();
$('#loading').hide('slow');
});
</script>
add this js code in your page this will help you.
You can use the following simple code
<?php
//header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
//long_process.php
for($i=1;$i<=3;$i++){
//do something
echo '<br>processing...';
ob_flush();
flush();
sleep(1);
}
echo 'CLOSE', 'Process complete';
?>
Or use as following
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<br />
<input type="button" onClick="startTask()" value="Start Long Task" />
<input type="button" onClick="stopTask();" value="Stop Task" />
<br />
<br />
<p>Results</p>
<br />
<div id="results" style="border:1px solid #000; padding:10px; width:300px; height:250px; overflow:auto; background:#eee;"></div>
<br />
<progress id='progressor' value="0" max='100' style=""></progress>
<span id="percentage" style="text-align:right; display:block; margin-top:5px;">0</span>
</body>
</html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
var es;
function startTask() {
es = new EventSource('bar2.php');
//a message is received
es.addEventListener('message', function(e) {
var result = JSON.parse( e.data );
addLog(result.message);
if(e.lastEventId == 'CLOSE') {
addLog('Received CLOSE closing');
es.close();
var pBar = document.getElementById('progressor');
pBar.value = pBar.max; //max out the progress bar
}
else {
var pBar = document.getElementById('progressor');
pBar.value = result.progress;
var perc = document.getElementById('percentage');
perc.innerHTML = result.progress + "%";
perc.style.width = (Math.floor(pBar.clientWidth * (result.progress/100)) + 15) + 'px';
}
});
es.addEventListener('error', function(e) {
addLog('Error occurred');
es.close();
});
}
function stopTask() {
es.close();
addLog('Interrupted');
}
function addLog(message) {
var r = document.getElementById('results');
r.innerHTML += message + '<br>';
r.scrollTop = r.scrollHeight;
};
</script>
Then create the following page. It has called in the index.php
bar.php
<?php
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache');
function send_message($id, $message, $progress) {
$d = array('message' => $message , 'progress' => $progress);
echo "id: $id" . PHP_EOL;
echo "data: " . json_encode($d) . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
send_message($i, 'on iteration ' . $i . ' of 10' , $i*10);
sleep(1);
}
send_message('CLOSE', 'Process complete');

Show alert with the content of a Database selection

I am very new to JavaScript what is related to it.
I have a set of dynamic rows and corresponding columns to those rows. In one column I have a button. When I click on it, it displays the results of a select query in another page based on the Posted Competence_ID.
The query works fine and I get correct results when I click on the button. However, what I would like to do now, is to display that message in an alert when the button is clicked and stay on the same page rather than opening a new tab..
Here is the relevant HTML code that shows the table I use:
echo "<table border='1' id='mycompstable' class='sortablee' cellpadding='0' cellspacing='0'>";
echo "<tr><th>ID</th><th>Competence Group</th><th>Competence Class</th><th>Competence Description</th><th>Own Evaluation</th><th>Manager's evaluation from last year</th><th>Target levels</th><th>Gap</th><th>Action</th><th class='unsortable'>Action ready target </th></tr>";
foreach($descs as $compi){
echo "<tr>";
echo "<td>".$compi['Competence_ID']."</td>";
echo "<td><p style='text-align: center;'>".$compi['Competence_Group']."</p></td>";
if(isset($compi['Competence_class'])){echo "<td>".$compi['Competence_class']."</td>";}else echo "<td><p style='text-align: center;'>-</p></td>";
echo "<td>".$compi['Competence_Description']."</td>";
echo "<td class='evaluation'>";
echo "<select class='ownlevelselect' id='ownlevelselect-.".$compi['Competence_ID']."' name='level-".$compi['Competence_ID']."' >";
if (isset($compi['ownlevel']) && $compi['ownlevel']!= '' && !empty($compi['ownlevel']) && $compi['ownlevel']!= 0) {
echo "<option selected value='".$compi['ownlevel']."' selected='selected'>".$compi['ownlevel']."</option>";
}
echo "<option value='' >--</option>";
echo "<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option>";
echo "</select>";
echo $compi['ownlevel'];
echo '<a test="'.$compi['Competence_ID'].'" onClick="showLevels('.$compi['Competence_ID'].');" target="_blank" href="'.INDEX.'?categ='.$_GET['categ'].'&action='.$_GET['action'].'&subaction=viewlevels'.'&levels='.$compi['Competence_ID'].'">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
echo "</td>";
Here is the code to retrieve the data:
function fetchlevels($Competence_id){
$this->query="SELECT * FROM levels WHERE comp_id=".$_REQUEST['levels'];
$tulos=$this->suoritaKysely();
return $tulos;
}
And here is the page that I want to show in the message:
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
echo '<input type="button" value="close" window onclick="window.close();">';
?>
Any kind of help would be very much appreciated
Here is a Ajax simulation in jsfiddle
http://jsfiddle.net/ncubica/Umxjb/
HTML
<i style='display:none' id="loadingPopup">Loading</i>
<table>
<tr>
<td data-id="td1"> row 1</td>
</tr>
<tr>
<td data-id="td2"> row 2</td>
</tr>
<tr>
<td data-id="td3"> row 3</td>
</tr>
</table>
javascript
$("table").on("click", function(event){
var $target = $(event.target);
if($target.is("td")){
var id = $target.attr("data-id");
makeAjax(id);
}
});
//simulating ajax
function makeAjax(id){
//you will have to use ajax an retrieve you json format
//i will simulate ajax only
$("#loadingPopup").show();
var _json = { id : id, value : "some value", description : "some description"};
setTimeout(function(){response(_json)}, 1000);
}
function response(_json){
$("#loadingPopup").hide();
alert(_json.id + " - " + _json.value);
}
CSS
table{font-family:arial; font-size:12px; width:100%}
table tr td{border-bottom:1px solid #CCC; padding:10px;}
Just an example based on the given info!
echo '<a onClick="showLevels('.$compi['Competence_ID'].');">';
echo '<img class="linkki" src="'.KUVAT.'paivita.gif" alt="'._("tiedot").'" title="'._("Click to view the description of each level?").'"/></a>';
Javascript/jQuery/Ajax
function showLevels(comp_id)
{
$.ajax({
type: "GET",
url: "process_file.php?comp_id="+comp_id,
success: function (result) {
alert(result);
}
});
}
process_file.php
<?php
//Your database Config.
$comp_id=$_REQUEST['comp_id'];
$this->query="SELECT * FROM levels WHERE comp_id=".$comp_id;
$tulos=$this->suoritaKysely();
//Proper Output Actions
$levels=$this->levels;
$comp=$this->compdesc;
echo "Levels explanation for the competence:".$comp['Competence_Description']."<br>";
echo "Level 1 = ".$levels[0]['lvl1'];
echo "<br>"."level 2 = ".$levels[0]['lvl2'];
echo "<br>"."level 3 = ".$levels[0]['lvl3'];
echo "<br>"."level 4 = ".$levels[0]['lvl4'];
echo "<br>"."level 5 = ".$levels[0]['lvl5'];
echo "<br><br>";
?>

retrieve id of table rows?

i have this script bellow to open table2 when clicking on the buttom 'more details'
<script>
$(document).ready(function() {
$('#Table1 tr').click(function(event){
$('#Table2').show();
alert($(this).attr('id'));
});
});
</script>
and this my code
<table id= "Table1" width='100%' border='1' cellspacing='0' cellpadding='0'>
$sql2=..
$sql3 = blabla ;
while($row3 =mysql_fetch_array($sql3)){
$sql4 = mysql_query (" SELECT $ww as place FROM data WHERE $ww =".$row3[$ww]." and id_user = ".$userid." ");
$row4 = mysql_fetch_array($sql4) ;
$string = "<blink > here </blink>" ;
$wnumber = $row3[$ww] ;
echo "<tr id= '".$wnumber."'><td style= 'text-align : center ;'>Week ".$row3[$ww]."
</td>" ;
echo "<td >".(int) $row3["percent"] ."% </td>";
echo "<td > "?><?php if($row4['place'] ==
$row3[$ww] and $row2['id'] == $userid ){ echo $string ; } else { echo "";} ;?><?php
"</td>";
echo "<td ><button class='showr'>More Details</button> </td></tr>";
//More Details when clicking on this buttom it open the table2
}
</tr>
</table>
this is second table
<?php
echo "<div id= 'Table2' style= 'display:none;'>";
echo "<table width='100%' border='1' cellspacing='0' cellpadding='0'>";
echo "<th> Week ".$wnumber."</th>";
echo "<th>try2</th>";
echo "<tr ><td>day</td>";
echo "<td>fff</td></tr>";
echo "</table></div>";
?>
*what i have now 5 rows with 5 buttoms .
*what it happen now is when clicking on every bottom it echo same '$wnumber' lets say 6.
however it defers from row to row ,
- script works good with alert of the id of which row is clicked.
- only the last buttom who works with the last id of row.
*what i want is every bottom works with its row id which echo the right '$wnumber'
* what i have tried is (make variable in the div)
echo "<div id= '".$wnumber."' style= 'display:none;'>";
instead of
echo "<div id= 'Table2' style= 'display:none;'>";
but didnt work.
hope its clear and there is solution of it.
EDIT : this source code
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#Table1 tr').click(function(event){
$('#Table2').show();
alert($(this).attr('id'));
});
});
</script>
<br />
<table id= "Table1" width='100%' border='1' cellspacing='0' cellpadding='0'>
<th >Weeks</th>
<th ><p></p></th>
<th > Your place</th>
<th > More Details</th>
<tr>
<tr id= '1'><td style= 'text-align : center ;'>Week 1</td><td style= 'text-align :
center ;'>33% </td><td style= 'text-align : center ;'> <td style= 'text-align :
center ;'><button class='showr'>More Details</button></td></tr><tr id= '6'><td
style= 'text-align : center ;'>Week 6</td><td style= 'text-align : center ;'>33%
</td><td style= 'text-align : center ;'> <td style= 'text-align : center
;'><button
class='showr'>More Details</button></td></tr><tr id= '13'><td style= 'text-align:
center ;'>Week 13</td><td style= 'text-align : center ;'>33% </td><td style=
'text-align : center ;'> <blink style= 'color:#990000 ;font-weight: bolder;' > 69
here </blink><td style= 'text-align : center ;'><button class='showr'>More
Details</button></td></tr></tr>
</table>
<br />
<div id= 'Table2' style= 'display:none;'><table width='100%' border='1'
cellspacing='0' cellpadding='0'><th> Week 13</th><th>try2</th><tr ><td>day</td>
<td>fff</td></tr></table></div>
<br /><br /> <br />
I tried your html code after correcting the missing td, tr.
And then clicking on each row / button displays the div.
Ensure you form proper html code in your php echo
Try something like this:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#Table1 tr').click(function(event){
$('#details').find('#week' + $(this).attr('id')).show();
// alert($(this).attr('id'));
});
});
</script>
<?php
$result = mysql_query($sql);
// save the results to an array so you can loop them twice
while($row = mysql_fetch_array($result)) :
$rows[] = $row;
endwhile;
?>
<table id="table1">
<tr>
<th>heading</th>
<th>heading</th>
<th>heading</th>
<th>heading</th>
</tr>
<?php foreach ($rows as $row) : // loop #1 to output the main table ?>
<tr id="<?php echo $row['ww'] ?>">
<td>value</td>
<td>value</td>
<td>value</td>
<td><button type="button">More details</button></td>
</tr>
<?php endforeach; ?>
</table> <!-- end table 1 -->
<div id="details">
<?php foreach ($rows as $row) : // loop #2 to output a table for each set of details ?>
<table id="week<?php echo $row['ww'] ?>" style="display: none">
<tr>
<th>Week <?php echo $row['ww'] ?></th>
<th>try2</th>
</tr>
<tr>
<td>value</td>
<td>value</td>
</tr>
</table>
<?php endforeach; ?>
</div> <!-- end details -->
I copy / pasted your code into a jsFiddle and it seems to work as expected. Clicking on the row sends an alert with the correct ID.
http://jsfiddle.net/JeeNN/
Is there something I'm missing in your intent here?
Note : Best practice would be to skip the inline CSS and add external styling for your tables. Also, valid HTML is a must.
Update:
I went ahead and formatted the php code you posted so it's a bit easier to read. There's some variables that aren't defined and a couple other issues, but I'm sure you have it correct in your php file.
I think that you're going to want to run the loop a second time to create the second table. In this second loop, echo out the second table once per loop - you'll end up with a bunch of tables (one per row plus the first table). Then simply swap the visibility of the tables as user's click each id.
Is that what you're looking for? If not, perhaps try to rephrase your question.
Here's that formatted code:
<table id="Table1" width='100%' border='1' cellspacing='0' cellpadding='0'>
<?php
$sql2 = [..];
$sql3 = [..];
$ww = ?;
while($row3 = mysql_fetch_array($sql3)){
$sql4 = mysql_query ("SELECT $ww as place FROM data WHERE $ww =".$row3[$ww]." and id_user = ".$userid." ");
$row4 = mysql_fetch_array($sql4) ;
$string = "<blink> here </blink>" ;
$wnumber = $row3[$ww];
echo "<tr id='".$wnumber."'>";
echo "<td style='text-align:center;'>Week ".$row3[$ww]."</td>";
echo "<td>".(int) $row3["percent"] ."% </td>";
echo "<td>":
if($row4['place'] == $row3[$ww] and $row2['id'] == $userid ){
echo $string;
} else {
echo " ";
}
echo "</td>";
//More Details when clicking on this buttom it open the table2
echo "<td ><button class='showr'>More Details</button></td>";
echo "</tr>";
} ?>
</table>
<div id= 'Table2' style= 'display:none;'>
<table width='100%' border='1' cellspacing='0' cellpadding='0'>
<tr>
<th> Week <?php echo $wnumber; ?></th>
<th>try2</th>
</tr>
<tr>
<td>day</td>
<td>fff</td>
</tr>
</table>
</div>

Can each row in an HTML table be numbered?

What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table:
I tried searching for this, and did not find anything that helped me.
Here is the PHP / HTML that is displaying the table:
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Created on</th>
<th style="width:65px;">Status</th>
<th>Actions</th>
</tr>
<?php
[...]
//Display the results
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
As you can see, it's displayed with a while loop.
If anyone knows a way to number each line in my table with jQuery or PHP, please help me :)
$trCounter=0;
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td>$trCounter++</td>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index.
I would go with PHP solution listed by Atul Gupta.
To add more - you also can to start iteration based on which page you are.
<?php
$i = ($page-1) * $itemsPerPage;
while(....)
{
echo $i;
$i++;
}
?>
if you are on the second page of your list would get something like 11,12,13,14,....
jQuery:
$(function () {
var i = 0;
$('table thead tr').prepend('<th>#</th>');
$('table tbody tr').each(function () {
i += 1;
$(this).prepend('<td>' + i + '</td>');
});
});
PHP
<tr>
<th>Sr. No</th> // Add header for counter
<th>Name</th>
...
</tr>
...
$i=1; // add counter -----------corrected-------------
while($info = mysql_fetch_assoc($result)){
//data
...
echo "
<tr>
<td>$i</td> // include counter to table
<td style=\"min-width: 87px;\">$name</td>
...
</tr>
";
$i++; // increment counter
}
Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?

Categories