how to get html table td attribute unique id with jquery - php

hi guys I'm trying go create tool tip for every HTML table cell do you guys have any idea how can i get td attribute id here
thanks a lot
jquery code sample
$(function () {
$(".test").hover(
function () {
var toolTipHtml = $("#ToolTipDiv").clone();
$(this).append(toolTipHtml);
toolTipHtml.show("slow");
},
function () {
var toolTipHtml = $(this).find(".tooltip");
toolTipHtml.hide();
toolTipHtml.remove();
}
);
});
echo "<table>";
while($row = mysql_fetch_array($result))
{
$id = $row['id_out_org'];
echo "<tr>";
echo "<td>" .$row['KG']."</td>";
echo "<td class='test'>" .$row['B']."</td>";
echo "<td >" .$row['B']."</td>";
echo "<td class='test'>";
echo "<div id = 'ToolTipDiv' class='tooltip' style='background-color: White; display: none; width: 20%;'>";
echo "Total: $ "; echo $totalp = $total + $fuel;
echo "</div>";
"</td>";
echo "</tr>";
}
echo "</table>";

Use a catch-all selector and then iterate over them:
$("td[id$=ToolTipDiv_]").each(function() {
$(this).attr('title', 'some tool tip');
});

Better you use this open source plug in
Tooltip
It might fulfill your need.
See examples here
$('#table td.test').tooltip();

To get the HTML and ID from every table cell:
$('td').each(function() {
var toolTipHtml = $(this).html(); // now you have the contents of the cell
id = $(this).attr('id'); // now you have the id
});

since you are using a Hoover you may use something like this
$('.tooltip').hover(function() {
alert(this.id);
// or to get the id of the row
var toolTipHtml = $("#"+this.id).clone();
});

Related

Table Sorter Open Child Row on row click

The code I have posted below shows a child row when you click on the value inside of a row, in this example with colindex of 2.
I was wondering what way I could make the same thing happen but when you click anywhere on the row. I am not sure on how to do this. The way I am creating my table is by using tablesorter and a php query. The display of the table works fine, I am just having issues finding documentation on displaying the child row when a row is clicked not the value.
My PHP:
<?php
foreach($report_tabs as $report) {
$tag=$report["tag"];
$title=$report["title"];
$hcols=$report["hdrcols"];
$cols=$report["datacols"];
$db_query=$report["dbquery"];
echo "<div id='my_test_table_tab' class='tab-pane active'>";
echo "<table id='test_table' class='table table-hover tablesorter'>";
echo "<thead>";
echo "<tr>";
// removed the hard coded column headers and took the ones from our query
global $hcols;
foreach($hcols as $column_header) {
echo "<th>$column_header</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//Use queried data to create each row of the table
$rowcount=0;
//Creating checker health table & filling with data
if ( isset($db_query)) {
while($row = mysqli_fetch_array($db_query)) {
$rowcount++;
// removed the hard coded column set and made it driven off of the array below
echo "<tr>";
$colindex = 0;
foreach( $cols as $column_name ) {
$val = $row[$column_name];
if ($colindex == 2) {
echo "<td style='text-align: left; width: 1pt;'><a href='#' class='toggle' onClick='drawChart(\"$val\");'>$val</a></td>";
$tempval = $val;
} else {
echo "<td style='width:100pt; text-align='right'>$val</td>";
}
$colindex++;
}
echo "</tr>";
echo "<tr class='tablesorter-childRow'>";
echo "<td colspan='3'>";
echo "<div id='$tempval' style='height: 400px;'></div>";
echo "<div id='fail$tempval' style='height: 400px;'></div>";
echo "</td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
echo "<h4>$rowcount rows retrieved</h4>";
echo "</div>";
}
?>
My TableSorter function to open based on value click:
<script>
// Table Sorter Options
$(document).ready(function(){
// Turns all tables with the 'tablesorter' class into tablesorter tables with the given widgets
$(".tablesorter").tablesorter({
// stickyHeaders - Keeps headers always visible when scrolling down
// filter - Adds filter boxes to each column
cssChildRow : "tablesorter-childRow",
widgets: ['stickyHeaders','filter'],
widgetOptions: {
stickyHeaders_offset : 50,
filter_placeholder : {search : ''},
filter_saveFilters: true,
pager_output: '{startRow} - {endRow} / {filteredRows} ({totalRows})',
pager_removeRows: false,
filter_childRows : true,
filter_cssFilter : 'tablesorter-filter',
filter_startsWith : false,
filter_ignoreCase : true
},
});
// Clear buttons
add_clear_buttons();
var table = $( '#my_test_table_tab' );
// hide child rows
table.find( '.tablesorter-childRow td' ).addClass( 'hidden' );
// Toggle child row content (td), not hiding the row since we are using rowspan
table.delegate( '.toggle', 'click' ,function() {
// use "nextUntil" to toggle multiple child rows
// toggle table cells instead of the row
$( this )
.closest( 'tr' )
.nextUntil( 'tr.tablesorter-hasChildRow' )
.find( 'td' )
.toggleClass( 'hidden' );
return false;
});
// Toggle filter_childRows option
$( 'button.toggle-combined' ).click( function() {
var widget_options = table[0].config.widgetOptions,
options = !widget_options.filter_childRows;
widget_options.filter_childRows = options;
$( '.state1' ).html( options.toString() );
// update filter; include false parameter to force a new search
table.trigger( 'search', false );
return false;
});
});
</script>
All you'd need to do is change the delegate function (why are you using such an old version of jQuery?), to point to the row instead of the link.
table.delegate( '.tablesorter-hasChildRow', 'click' ,function() {
I set up this demo, which is using a newer version of jQuery - the delegate function has been deprecated, so use on instead:
$table.on('click', '.tablesorter-hasChildRow', function() {

How to take id of dynamic <p> tag and to change its background color when clicking on it?

following is the code
foreach($this->categoryResult as $CatResult)
{
echo "<div id=".$CatResult['id']." onclick='$(this).css('background-color','#1adec9')'><p id=".$CatResult['id']." class='CatgrySelect' onClick='load_subcategory(".$CatResult['id'].")'>".$CatResult['description']." > </p></div>";
echo "<input type='hidden' class='CatID' name='CatID' value=".$CatResult['id'].">";
//echo $CatResult['id'];
}
There is a concept called Unobstrusive Javascript.
$(document).on('click', 'p.CatgrySelect', function(eV) {
var pItem = $(this);
var divItem = $(this).parents("div:first");
pItem.css({"background-color":"#abc"});
divItem.css({"background-color":"#cba"});
});
If you can reference any other parent DOM element that contains this dynamic DOM element you can replace it for document on the event listener.
try this:
echo "<div id=".$CatResult['id']." onclick='$(this).css(\'background-color\',\'#1adec9\')'>
adding a '\' before something like a quote general tells a text parser that you'd like avoid splitting the string at that point
looks like you have two IDS with the same name.. that is invalide.. ID should always be unique
try this
foreach($this->categoryResult as $CatResult)
{
echo "<div><p id=".$CatResult['id']." class='CatgrySelect' >".$CatResult['description']." > </p></div>";
echo "<input type='hidden' class='CatID' name='CatID' value=".$CatResult['id'].">";
//echo $CatResult['id'];
}
javascript
$('document').on('click', 'p.CatgrySelect', function() {
var p = $(this);
var div = p.parent();
p.css({"background-color":"#abc"});
div.css({"background-color":"#cba"});
});
foreach($this->categoryResult as $CatResult)
{
echo "<div id='".$CatResult['id']."'><p id='".$CatResult['id']."' class='CatgrySelect'>".$CatResult['description']."</p></div>";
echo "<input type='hidden' class='CatID' name='CatID' value='".$CatResult['id']."'>";
//echo $CatResult['id'];
}
$(".CatgrySelect").click(function(){
$(this).parent().css('background-color','#1adec9');
});
try this:
foreach($this->categoryResult as $CatResult)
{
echo "<div id='".$CatResult['id']."'><p id='".$CatResult['id']."' class='CatgrySelect'>".$CatResult['description']."</p></div>";
echo "<input type='hidden' class='CatID' name='CatID' value='".$CatResult['id']."'>";
//echo $CatResult['id'];
}
try this jquery/javascript:
$(".CatgrySelect").live('click',(function(){
$(this).parent().css('background-color','#1adec9');
});

jQuery Sortable PHP

I am using jQuery sortable to manipulate image order and write to a DB. That functionality works well.
PHP
echo "<div class='revisionNum'>";
echo "<ul id='sortable_" . $count ."'>";
while($row = mysql_fetch_array($result)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $galleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='item_{$row['id']}' >";
echo '<img class="sortImage" src="'. $sortPath .'"/>';
echo "<p>" . $sortImageName . "</p>";
echo "</li>";
}
echo "</ul>";
echo "</div>";
jQuery
//make sortable
$(".revisionNum").each(
function(e) {
num = e + 1;
$("#sortable_" + num).sortable(
{stop:function(i) {
serial = $("#sortable_" + num).sortable("serialize");
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: serial
});
},
opacity:1.0,
//cursor: move
});
});
MYSQL
foreach($_GET['item'] as $key=>$value) {
mysql_query(" UPDATE galleryimage
SET sort = '{$key}'
WHERE id = '{$value}'
");
}
The issue is when I have multiple <div class=''revisionNum> i am only grabbing the serial = $("#sortable_" + num) of the last UL if the [.revisionNum], not the actual UL that I am sorting. Thanks for the help on this. Let me know if further clarification is needed.
I am not sure I fully understand your question, but I think you are looking for the following:
The variable num will change every loop you make in the each-loop. But at the end it will have the value of the last loop. Because num seems to be a global variable you can't call it in the stop function. Then it will just use the last value it had. The value of the last loop. (Explains your problem)
To solve this I recommend to change your code to:
$(".revisionNum").each(
function(e) {
$(this).children("ul").sortable(
{stop:function(i) {
num = $(this).children("ul").attr("id").replace("sortable_", "");
serial = $(this).children("ul").sortable("serialize");
...
$(this) refers to the $(".revisionNum") you are looping through and it will be remembered, also in the stop function.

can getJSON be used to get a value from an html tag id already rendered by a page?? json_decode?

what i mean by this is after an html page is rendered, how can i get the value by using the html tag id??
ex: get the value of date by using td_date in my JS function??
below the code that puts the data on the page: listSuccess.php
foreach ($pager->getResults() as $msg)
{
echo "<tr id='td_id' value='$msgId'</tr>";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "<td class='td_show_contact_item' align='left' id='td_date'>".$date."</td>";
<td align='left' id='td_subject'>
<a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?></a>
</td>
echo "<td class='td_show_contact_item' align='left' id='td_from'>".$unique_code_from."</td>";
echo "<td id='block_url'>( ".$block_url." )</td>";
echo "</tr>";
++$cursor;
}
so in my JS:
function ax_get_new_msg_details()
{
var mTimer;
$.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data)
{
var messageExists = $('#' + data.td_id).length > 0;
if (!messageExists)
{
mTimer = setTimeout('ax_get_new_msg_details()',30000);
var str='<tr id="' + data.td_id + '">';
str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>';
str += "<td align='left' id='td_subject'><a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'>"+data.td_subject+"</a></td>";
str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +"</td>";
//str += "<td id='block_url'>"+data.block_url+"</td>";
str +='<tr>';
var tbl = $('#td_date').parents('table');
$(tbl).append(str);
}
});
}
then newMessageDetails.php in my actions.class.php
public function executeNewMessageDetails(sfWebRequest $request)
{
$profile_id = $this->getUser()->getAttribute('profile_id','zero');
$new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
if (count($new_msgs) >= 1)
{
foreach ($new_msgs as $row)
{
$date = $row->getCreatedAt();
$subject = $row->getSubject();
$from = $row->getProfileIdFrom();
$id = $row->getId();
$uc_record = RcProfileTablePeer::getById($from);
$uc_from = $uc_record->getUniqueCode();
//$block_url = 'Block User',"blocklist/block?unqiue_code=$uc_from",'class=link_medium_blue');
}
$output = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_id" => $id);
}
else
$output = "";
return $this->renderText(json_encode($output));
}
the data that i get from the JS function is correct but i need to somehow know that what is actually already on my page ie what was rendered already differs from what json returns and if data differs...update the page with the new json data
any advice?
Why not include your td_id in your tr tag and just compare the incoming id with the existing id?
var str='<tr id="' + data.td_id + '">';
Then in your update put this if condition around your code:
var messageExists = $('#' + data.td_id).length > 0;
if (!messageExists) {
// your existing code
}
Personally I use firefox and the web developer tool bar it not only allows you to see the source code but also allows you to view the generated source code, plus lots of other very useful tools hope this helps you.

connecting jquery attr to PHP Mysql?

a PHP table populates its data from mysql, When a user clicks .button a drop down table row menu appears where user has ability to add item to cart, the name of the item in cart should be the mysql entry $sound['downloadlink'] located in the table row above .mp3buy, It is adding the actual string "$sound['downloadlink']" instead of what the mysql entry for download link should be.
PHP Table
<?php
while($sound=mysql_fetch_assoc($records)){
echo "<tr class='adder'>";
echo "<td width='40' class='player'> <a href='beats/".$sound['downloadlink']."' class='sm2_button'>Play/</a></td>";
echo '<td width="250" class="name">'.$sound['name'].' <span class="red date">'.$sound['date'].'</span></td>';
echo "<td width='88' class='bpm'>".$sound['bpm']." B.P.M.</td>";
echo "<td width='72' class='length'>".$sound['length']."</td>";
echo "<td width='275' class='keywords'>".$sound['keywords']."</td>";
echo "<td width='96' class='buy'><img class='button' src='99cents.png'/></td>";
echo "</tr>";
}
?>
Jquery:
$('#mytable').on('click', ".button", function () {
var thisRow = $(this).parents('tr.adder');
var hasNextRow = thisRow.next('tr.added').length;
if (hasNextRow) {
thisRow.next('tr.added').remove();
} else {
$(this).parents('tr.adder').after('<tr class="added"><td height="100" colspan="6" ><img class="mp3buy" data-product-id=$sound["downloadlink"] src="mp31.png"/></td></tr>');
}
});
$('#mytable').on('click', ".mp3buy", function () {
var flag = $(this).data('flag');
simpleCart.add({
name : $(this).attr("data-product-id"),
price : .99,
quantity : (flag ? -1 : 1)
});
$(this).attr("src", flag ? "mp31.png" : "mp32.png");
$(this).data('flag', !flag);
});
Firstly, your PHP in your jQuery block is not getting parsed as you need to write <?= $sound["downloadlink"] ?> (PHP 5.4 syntax).
However, that's not your solution as you want the correct link for the product, not one fixed value. You could change your button so that it knows the link, as follows:
<img class='button' src='99cents.png' data-link='".$sound["downloadlink"]."'/>
Then you need to make quite a few jQuery changes:
$('.button').on('click', function () {
var thisRow = $(this).parents('tr.adder');
var hasNextRow = thisRow.next('tr.added').length;
if (hasNextRow) {
thisRow.next('tr.added').remove();
} else {
$(this).parents('tr.adder').after(
'<tr class="added"><td height="100" colspan="6" ><img class="mp3buy" data-product-id="'
+ $(this).data('link')
+ '" src="mp31.png"/></td></tr>'
);
}
});
$('#mytable').on('click', ".mp3buy", function () {
var flag = $(this).data('flag');
simpleCart.add({
name : $(this).data("product-id"),
price : .99,
quantity : (flag ? -1 : 1)
});
$(this).attr("src", flag ? "mp31.png" : "mp32.png");
$(this).data('flag', !flag);
});
That's roughly right but I might have missed something. The idea is that you keep your data in your HTML then use your script to manipulate the data. Don't put your data in your script. Also, it doesn't really make sense to transfer the value of the data-downloadlink attribute over to a data-product-id attribute. It would be better to refer to the original value.

Categories