Use existing javascript to trigger if else in php - javascript

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

Related

Counter in Javascript closure not incrementing

I am writing some JavaScript code, where I am using a closure for a counter. The code is given below:
function userHandler(){
var counter = 0;
var limit = "<?php echo ($_SESSION['limit']); ?>";
return function(){
var args = {
n : $('#name').val(),
s : $('#ssn').val(),
i : $('#id').val()
};
$.post("adduser.php",args,function(data){
var response = JSON.parse(data);
console.log(args);
if(response.status == 0){
counter += 1;
alert(counter);
if (counter == limit){
$('#limit').text(limit-counter);
}
}
console.log(data);
});
};
}
var opcall = userHandler();
$('#addUser').on("click", opcall);
I am using this guide to write the code. The problem is, my counter always shows 1 in the alert box. It does not increment. Am I not calling the inner method correctly?
EDIT: There's a span in the HTML which is receiving the limit-counter value:
<p>
<span>Add User</span>
You can add <span id="limit"></span> more users. <a href='<?php echo $root; ?>editaccount.php?action=addOp'>Add another operator?</a>
</p>
It always shows (20-1)=19 every time I submit the form which uses the Javascript.
UPDATE: Thank you for pointing out my mistake, after clicking the "addUser" button, another page was opening with a confirmation message, where a link had to be clicked to return to the original page. I moved the confirmation message to the original page and now it works fine!!

Countdown JS+PHP, what's wrong?

I'm trying to make this function work but i don't know what's wrong and i'm not really good at js.
I want to do call my timer function with number of seconds to countdown from the span id "count".
Example:
<p id="hello">Wait <span id="count">5</span> secs</p>
<?php
echo '<script type="text/javascript">'
, 'timer(5);'
, '</script>';
?>
<script>
function timer(tiempo){
setInterval(function() {
tiempo--;
if (tiempo >= 0) {
span = document.getElementById("count");
span.innerHTML = tiempo;
}
// Display 'counter' wherever you want to display it.
if (tiempo === 0) {
window.location.reload();
clearInterval(tiempo);
}
}, 1000);
});
</script>
What's wrong?
Define the function before it's called:
<script type='text/javascript'>
function timer(tiempo){
setInterval(function() {
tiempo--;
if (tiempo >= 0) {
span = document.getElementById("count");
span.innerHTML = tiempo;
}
// Display 'counter' wherever you want to display it.
if (tiempo === 0) {
window.location.reload();
clearInterval(tiempo);
}
}, 1000);
}
</script>
<p id="hello">Wait <span id="count">5</span> secs</p>
<?php
echo '<script type="text/javascript">'
, 'timer(5);'
, '</script>';
?>
The problem here has nothing to do with the PHP.
In JavaScript in an HTML document:
Function declarations are hoisted
All scripts share the same working environment
However:
Functions are not hoisted from a later script to an earlier script
You are running a script that tries to run the timer function.
Then you are running a script that defines that function.
It doesn't exist in time.
Either:
Swap the order of the <script> elements or
Remove the first </script> tag and the second <script> tag
Check the demo.
HTML
<p id="hello">Wait <span id="count">5</span> secs</p>
<input type="button" value="start" id="start" />
Jquery and JS
$('#start').click(function(){
showTimer(5);
});
function showTimer(tiempo){
setInterval(function() {
tiempo--;
if (tiempo >= 0) {
span = document.getElementById("count");
span.innerHTML = tiempo+'.....';
}
// Display 'counter' wherever you want to display it.
if (tiempo === 0) {
// window.location.reload();
clearInterval(tiempo);
alert('movie starts......');
}
}, 1000);
}
DEMO
http://jsfiddle.net/nadeemmnn2007/jeps93gy/

My onclick does not work right the way it should be

I have this function
<?php
for($i = 1; $i <=9; $i++){
print("<div id='cover'>");
for ( $j = 1; $j <= 9; $j++){
if($i % $j == 8 || $i < $j || $i == $j){
print("<div class='colors' onClick='hello($i, $j)'>");
} else {
print("<div class='pinks' onClick='hello($i, $j)'>");
}
print($i ."+". $j ." ");
print("</div>");
}
print("</div>");
}
?>
Which produces a bunch of div with numbers on it. I want to be able to click on it, and show the result of adding two numbers.
I have this JavaScript function for that
function hello(r, t)
{
$("div.colors, div.pinks").html(r+t);
}
but I do not know how to get only the one div i click on. How can I do that?
Assuming you only want to calculate the element on which the user has clicked, then the method should be more like this:
function calc(element, r, t)
{
element.innerHTML = r+t
}
while the method call ofc would be:
<div>3+2</div>
See this fiddle for example.
http://jsfiddle.net/m9wkr0vz/
To allow more complex calculations without providing methods for every combination, you could use javascripts ability to evaluate expressions given:
function calc(element)
{
element.innerHTML = eval(element.innerHTML);
}
with
<div>(7+1)/(2+2)</div>
see this fiddle: http://jsfiddle.net/u20bgx83/

Zclip not working

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");

JS: Counter decrease, at hide()

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.

Categories