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.
Related
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() {
I'm creating web page that fetch values from database, there are several values will be display. On each value, it will have textarea and button Tweet below. I want when user click on button tweet, it will catch the value from textarea above that button. For now, it will catch only the value from the first textarea when user click on button Tweet (all buttons).
Here is my code
PHP
while($row=mysql_fetch_array($sql)){
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' id='tweet'
href='#'>Tweet</a>";
}
Javascript
$("#tweet").bind('click', function(){
var text_tweet = $("#text_tweet").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
Can anyone help me to solve this problem?
Thank in advance.
You need to distinguish between each row that is being looped out. Here's an alternate approach assuming that $row has an id.
PHP
while ($row = mysql_fetch_array($sql)) {
echo "<textarea style='margin-bottom:10px;' id='text_tweet_" . $row['id'] . "' name='text_tweet_" . $row['id'] . "' cols='61' rows='5'></textarea>";
echo "<a onclick='doSomething(" . $row['id'] . ")' style='text-decoration: none; color: #000000;' id='tweet_" . $row['id'] . "' href='#'>Tweet</a>";
}
JS
function doSomething(id) {
var text_tweet = $("#text_tweet_" + id).val();
if (text_tweet == "") {
alert("Please fill out something");
} else {
save_tweet(text_tweet);
}
}
First off, if you're going to try and grab more than one element on a page, you can't use id as that's reserved for single elements - you should never have more than one element with the same id
First, I would change it so that each element has a class called 'tweet' on it. You will also need to add the jQuery $(function(){}) around it. That function tells the browser not to run that JavaScript until the page and all elements have completely loaded.
I would also make sure to add a container around both the elements, this will make it easier for you to actually grab the textarea that is beside the the link.
Here's how I would handle it:
while($row=mysql_fetch_array($sql)){
echo "<div>";
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' class='tweet'
href='#'>Tweet</a>";
echo "</div>";
}
And then the javascript:
$(function() {
$(".tweet").bind('click', function(){
var text_tweet = $(this).parents('div:first').find("textarea").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
});
The reason we do $(this).parents('div:first').find("textarea").val() is because we want to grab the textarea within that containing div only; otherwise, jQuery will grab the first textarea value in the array.
this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.
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();
});
hey guys, im having some trouble...
i'm able to capture the first button on the page, but there are a total of 10 buttons. When I click on any of those 10 buttons, only the first button's value is called and the other ones don't update. is there a way to capture all of the buttons so they each have their own independent value and update their values so jQuery's ajax function gets the new one? the buttons are being created out of a multidimensional array loop.
<?php
$characters = $char->getCharactersListFromAccountId($_SESSION['acctid']);
foreach ($characters as $key) {
if(is_array($key)){
echo "<input class=\"button\" type=\"button\" href=\"javascript:void(0)\" value=\"Show\" style=\"vertical-align: top\" />";
echo $char->getFaction($key['guid']), " ";
echo $char->getClass($key['guid']), " ";
echo "<span class='style'>", $char->getLevel($key['guid']), "</span> ";
echo "<span class='style'>", $key['name'], "</span>";
echo "<input class=\"GUID\" type=\"hidden\" name=\"GUID\" value=\"";
echo $key['name'];
echo "\" />";
echo "<br>";
} else {
echo "<br>";
echo "<b><h1>My Characters: $key</h1></b><br />\n";
}
}
?>
<div id="view" style="display: none;"></div>
<script>
$(".button").livequery('click', function(event) {
var GUID = $('.GUID').val();
$("#view").html('Retrieving...');
$("#view").show("slow");
$.ajax({
type: "POST",
data: "ID=" + GUID,
url: "character.php",
success: function(msg){
$("#view").html(msg);
}
});
});
</script>
From what I can gather, the issue you are facing is that you need to send only the GUID which belongs to the clicked button - i.e. the next one in the document. If I'm correct, you can try this:
$(".button").livequery('click', function(event) {
// get the next GUID value
var GUID = $(this).nextAll('.GUID:first').val();
...
Also, is there any real need to use livequery for that?