If I have a normal
<?php echo "Today (".mysql_num_rows($query)."); ?>
That turns out as Today (10) if there's 10 rows.
Now under this counter I have an while() that outputs all the rows inside a <tr>.
In a <td> inside the tr i have this delete button, which hides closest 'tr'.
How can I when you hide the 'tr' the Today(10) will decrease to Today(9) ?
--
I dont think its possible with the current counter (mysql_num_rows), but maybe if you count how many 'tr' there is, in the Today(), you could make something that decreases, but I do not know how to do this. Although this is just an thought..
Alter your PHP accordingly:
<?php echo 'Today (<span class="counter">' . mysql_num_rows($query) . '</span>)'; ?>
And have something like this for your delete button:
$('#theTable').delegate('button.delete', 'click', function (event) {
$(this).closest('tr').slideUp();
$('span.counter').text(function (index, val) {
return (parseInt(val, 10) - 1);
});
event.preventDefault();
});
Note the use of delegate: It's much more efficient than it would be to bind an event handler to each delete button.
You'll have to alter the selector for your table and your delete button accordingly.
you can do something like this :
$('.deleteButton').click(function() {
var curn = parseInt($('.counter').text(), 10);
if(curn - 1 >= 0)
$('.counter').text(curn - 1);
});
and change your echo to
<?php echo "Today (<span class='counter'>".mysql_num_rows($query)."</span>)"; ?>
Wrap the number so you can select is easily:
<?php echo 'Today (<span id="number">'.mysql_num_rows($query).'</span>)'; ?>
Then when a delete button is clicked:
// Get the number element once
var num = $('#number');
// Set an onclick event on your button
$('.delete').click(function(){
// Find the closest table row and remove it
$(this).closest( 'tr' ).remove();
// num.text() will get the text inside the number element
// parseInt is used to convert it from string to int
// subtract 1 to update the number
var newNumber = parseInt( num.text(), 10 ) - 1;
// And set the new number text
num.text( newNumber );
// Stop the default browser action - might cause the page to reload or to scroll
return false;
});
try it at: http://jsfiddle.net/xMZgv/7/
Today(<span id="counter">3</span>)
<table>
<tr><td>hello</td><td>delete</td></tr>
<tr><td>world</td><td>delete</td></tr>
<tr><td>hi</td><td>delete</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js"></script>
<script>
$(function() {
$('table tr').find('td:last').click(function() {
$(this).parent().remove();
$('#counter').html($('#counter').html() - 1)
})
})
</script>
Output your counter to a JavaScript var and use it in your loop and Today() function call. I'm assuming you're trying to output a client side function call from the server?
<?php echo "var count=".mysql_num_rows($query).";Today(count);" ?>
In your delete handler decrement count and call Today(count) again.
Related
How could I change the NaN text to 0?
Im using a function to show a variable price calculator in a Woocommerce store.
Until some variable are selected Im getting a NaN result, once selected it works fine so I would like to just change the NaN text to zero.
This is the code:
// hook this on priority 31, display below add to cart button.
add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_variation_price', 31 );
function woocommerce_total_product_variation_price() {
global $woocommerce, $product;
// setup base html... We are going to rewrite this with the standard selected variation
echo sprintf('<div id="product_total_price" style="margin-bottom:20px; display: block;">%s %s</div>',__('Precio Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
?>
<script>
jQuery(function($){
var currency = currency = ' <?php echo get_woocommerce_currency_symbol(); ?>';
function priceformat() {
var product_total = parseFloat(jQuery('.woocommerce-variation-price .amount').text().replace(/ /g ,'').replace(/€/g ,'').replace(/,/g ,'.')) * parseFloat(jQuery('.qty').val());
var product_total2 = product_total.toFixed(2);
var product_total3 = product_total2.toString().replace(/\./g, ',');
jQuery('#product_total_price .price').html( currency + ' ' + product_total3);
}
jQuery('[name=quantity]').change(function(){
priceformat();
});
jQuery('body').on('change','.variations select',function(){
priceformat();
});
priceformat();
});
</script>
<?php }
Thanks in advance
Just check if the variable is NaN and if it is set it to zero.
if(isNaN(product_total)){
product_total = 0
}
A simpler way to do this is:
product_total = product_total || 0
Because product_total is NaN it will assign it to 0. Be careful though because 0 is also considered a falsey value in this scenario.
I am seeking to increment a variable (counter) each time a DIV is clicked.
The variable of the counter is used to select a question_id in another table so I need to reference it both in JAVASCRIPT and PHP .
Here is my code:
<script type="text/javascript">
var i= 1;
$(document).ready(function(){
$("#input01, #input02, #input03, #input04, #input05").click(function(){
var value01 = $(this).attr('value');
var value02 = i;
$.post('input_answers.php',{value:value01,id_question:value02});
var value02 = i+1;
});
});
</script>
Below is the query to insert the data ('input_answer.php')
mysqli_query($connect, "INSERT INTO `answers` VALUES ('".$_POST['id_question']."' , '".$_POST['value']."' ) ");
My problem is that I'd like to incremen a variable to display a new question each time one of the DIV is clicked.
Thank you for your help.
Correct way to pass mutliple values to server is:
$.post('input_answers.php',{value:value01, id_question:value02});
Your case:
$.post(
'input_answers.php', // URL
{value:value01}, // data passed to server
{id_question:value02} // third argument, which is NOT passed to server
);
Update: correct way to increase your counter is to wait until request is over and add 1 in a callback:
$.post(
'input_answers.php',
{value:value01, id_question:value02},
function () {
// as your i is a global variable you can increase it here
i += 1
}
);
Going through the other posts i must either have something wrong with my code or my logic is fundamentally flawed.
So what happens is i have a series of array elements that get called/written, these array elements need to have sub elements modified by java script.
Everything was workign before i needed to add an array i.e i was using a single element selector ID for the functions below and got the correct results. However after adding unique ID's in a loop it doesn't want to change.
So here's what happens, I have a separate div that is hidden. This prints out how many elements are in the array as its a PHP session variable. $Carray is a count function and works correctly.
<div class="Carray"><?php echo $Carray;?></div>
Then as the items are looped they add an array ID
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div id="subP_<?php echo $arrayID;?>" class="booking_action">-</div>
<div id="booking_people_<?php echo $arrayID;?>" class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div id="addP_<?php echo $arrayID;?>" class="booking_action">+</div>
<?php }} ?>
Then in Javascript i call a loop function that counts through however many $Carray elements there are and then corresponds the correct function actions to the correct div ID's
//get the counted array variable and force as an int
var js_var = parseInt($('.Carray').html(),10);
// loop for however many array elements there are
for (i = 0; i < js_var; i++){
// get the amount of people from a field
var ppl_P = parseInt($('#booking_people_'+i).html(),10);
// subtract 1 person and then change the output to match the new people count
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
****************************** EDIT **********************
So based on Jimmi Elofsson answer which works beautifully, i want to expand this to effect elements that are not inside the parent/child selectors. The selector is '.booking_price_inner' which is another div stored elsewhere. I am assuming the line that needs the correct syntax is the marked line.
The '.booking_base_price' is within the parent/child element.
$(".subPerson").click(function() {
// Subtract Person
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
//Change price
var totalPriceS = subPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceS); <-------
});
$(".addPerson").click(function() {
//Add person
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1;
$(this).parent().children('.booking_people_number').html(addPeopeCount);
//Change price
var totalPriceA = addPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceA); <------
});
// get the number of people in the specific array
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
//get the base price
function getBasePrice(peoplePrice){
return parseInt(peoplePrice.children('.booking_base_price').html());
}
Markup
<div id="<?php echo $arrayID;?>" class="booking_people">
<div class="booking_date_header">People:</div>
<div class="subPerson booking_action">-</div>
<div class="booking_people_number"><?php echo $list["i_quantity"] ?></div>
<div class="addPerson booking_action">+</div>
<div class="booking_base_price"><?php echo $list["i_base_price"] ?></div>
</div>
<div class=spacer></div>
<div class=cost>
<div class=booking_price_inner></div>
</div>
If you don't mind, I did some changes in your code.
you could make your add/substract element use the same click function with the help of some DOM traversing. That way you wouldnt need the CArray to keep track of the buttons.
Javascript:
// subtract 1 person and then change the output to match the new people count
$(".subPerson").click(function() {
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;// Substract by one.
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
});
// Add 1 person and then change the output to match the new people count
$(".addPerson").click(function() {
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1; // Increase by one.
$(this).parent().children('.booking_people_number').html(addPeopeCount);
});
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
PHP:
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div class="booking_people_item" id="<?php echo $arrayID;?>">
<div class="subPerson booking_action">-</div>
<div class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div class="addPerson booking_action">+</div>
</div>
<?php }} ?>
I added a div wrapper around your elements called booking_people_item.
from what I see - you're definig click functions in a loop. Those click functions have a reference to a ppl_P variable. When you define the click, it seems OK. But when the click is triggered, the ppl_P variable is already set to the value from loops last iteration. So, whenever you call that click function, it always has the same result, doesn't it?
The proper way to do it would be to pass this ppl_P variable as a parameter, so you don't have a reference to a variable that was already changed in the other scope. Something like:
function addClickFunction(i, ppl_P){
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
And then use this function inside the loop:
var ppl;
for (i = 0; i < js_var; i++){
ppl = parseInt($('#booking_people_'+i).html(),10);
addClickFunction(i, ppl);
}
This hasn't been tested, but I'm pretty sure you'll get the point :)
I have the following script within a page on my site which adds + - buttons to a qty entry field:
<script language="javascript">
jQuery.noConflict();
jQuery(document).ready(function() {
var $cartAdd = jQuery('#cartAdd')
, $quantity = $cartAdd.find('input');
$cartAdd.append('<div class="inc button">+</div><div class="dec button">-</div>');
jQuery(".back").change(function(){
$quantity.val(1).change();
});
$cartAdd.click(function(evt) {
var $incrementor = jQuery(evt.target)
, quantity = parseInt($quantity.val(), 10);
if($incrementor.hasClass('inc')) {
quantity += 1;
} else if($incrementor.hasClass('dec')) {
quantity += -1;
}
if(quantity > 0) {
$quantity.val(quantity);
xhr.getPrice();
}
jQuery(".back").change(function(){
xhr.getPrice();
});
});
});
</script>
I want to be able to hide/unhide a div when var $cartAdd goes above 1
I tried using something like
var $cartAdd = jQuery('#cartAdd')
, $quantity = $cartAdd.find('input');
<?php $trigger = "<script>document.write(quantity)</script>"?>
followed by
<?php echo $trigger;?>
and i expected that to echo the value in the entry box but it didn't.
Is it achievable?
You must understand that all php scripts are executed BEFORE the javascript.
What's wrong with simply grabbing the quantity and hiding if needed?
if( $('#cartAdd').find('input').val() > 1 )
{ $('#div_we_want_to_hide').hide() }
just put that inside a document.ready and it should work fine
Hi friends I am trying to implement click to copy using zclip.
I am having different ids for same class so initially i am finding the id of the element on which i clicked and applying zclip to that element.
$(".coupon_code_text").on('click', function (e) {
pos = "#" + $(this).attr("id");
e.preventDefault();
clktocpy();
function clktocpy(){
$(pos).zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: function () {
return $(pos).text();
}
});
}
})
The following is the php part where I am generating different ids for the same class.
<?php
$count = 0;
foreach($coupons as $value)
{
$count = $count +1;
<div class="coupon_code" >
<a class="coupon_code_text" id ="copypath-<?php echo $count;?>">
<?php echo $array['coupon_code'];?>
</a>
</div>
<?php}?>
Remember that in order to get by id using jQuery you need to append a # to the string.
Like the following #myId, your variable pos only contains the id without the #.
Line 2, fixed
pos = "#" + $(this).attr("id");