jQuery detect when total value of counters are 0 - javascript

I have a slight problem that I do not know how to approach due to my lack of Javascript experience. Basically I have two or more counters that each count upwards or downwards separately. I want to run a function when all of the counters total value equals to 0
But I do not know how to extract that value from the functions that someone wrote for me.
Here is a jsFiddle for the counters
http://jsfiddle.net/RoryMcCrossan/puJ6G/1015/
jQuery(document).ready(function () {
$('.qtyplus').click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
});
$(".qtyminus").click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal) && !currentVal == 0) {
$field.val(currentVal - 1);
} else {
$field.val(0);
}
});
});
Many thanks! :)

Firstly we can write a new function which checks all our counters and adds their values together:
function checkCounters() {
var result = 0;
// Loop through each "qty" input element
$('.qty').each(function() {
// Add the value of the input to our result
result += +this.value;
});
if (result === 0)
// Your function should be triggered here
console.log("Result is 0");
else
console.log("Result isn't 0, result is " + result);
}
We can then call this function whenever we update the value of a counter:
...
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
checkCounters();
JSFiddle demo.

Related

JS JQ How to reduce total value when click on button

I only know how to make total value using jQuery, but I don't know how to reduce the value.
Is there anyway to make total value be able to reduce price when click on image too?
I tried this but it doesn't work
$(document).ready(function() {
$('.items_img').click(function() {
var path = $(this).attr('data-title');
addImage(path, 500, 500, 0.5, -90, 3);
var name = $(this).attr('data-name');
totalname.push(name);
if (totalname == '') {
$('#name').val('');
} else {
$('#name').val(totalname);
} else if ($(document).click(function(deleteObject())) { // I did this and it doesn't work
$('#name').reduce('');
}
$('#name').val(totalname);
var price = $(this).attr('data-target'); totalprice = totalprice + parseInt(price);
if (totalprice == 0) {
$('#cost').val('');
} else {
$('#cost').val(totalprice);
}
}
})
});
function deleteObject() {
canvas.getActiveObject().remove();
}

How to break from Jquery click callback function

I am making my own version of simon Game, but the callback function inside click is not existing after user press wrong input. As a result function handler.patternRepeatPlayer() is getting called recursively for each element of array pattern.I want a solution to break from the else after callinghandler.patternRepeatPlayer just once. The program is working fine in strict mode, but only in non-strict mode inside else , I am not able to break from else.
-- can access the project on Git.
https://github.com/santosh1357/simonGame.git
The flow is like from html -> Function simonnGame.PatternGen from PatternGen -> handler.PatternRepeatPlayer -> PatternRepPlayer -> PatternMatcher -> userInput(here if wrong user input in non-strict mode) -> patternRepeatPlayer
This case is failing as in this case else is not existing after calling the function only once.
//Problematic Function.
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10); userPattern.push(id);handler.effect(id);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once****
return ;
}
}
//End Problematic Functiom
I think there is some misunderstanding on how click callback functions work.
//Fullcode
var simonGame = {
COUNT: 0,
PATTERN: [],
SOUND:[{file:'sounds/sa.mp3'},{file:'sounds/re.mp3'},{file:'sounds/ga.mp3'},{file:'sounds/ma.mp3'},{file:'sounds/pa.mp3'},{file:'sounds/dha.mp3'},{file:'sounds/nee.mp3'}],
patternGen: function(){
var randomId;
randomId = Math.floor(Math.random() * 7);
simonGame.PATTERN.push(randomId);
if(simonGame.COUNT > 20){
alert("You have won the game!!");
window.location.reload(true);
}
simonGame.COUNT += 1;
//debugger;
//console.log("increase count true calling count display " + simonGame.COUNT);
handler.countDisplay();
//console.log("count gen true calling patternPlayer with PATTERN " + simonGame.PATTERN );
handler.patternRepeatPlayer();
}, //close patternGen
patternMatcher: function(genPattern){
//console.log("inside patternMatch");
var genPattern = simonGame.patternGen;
//setTimeout(function(){
//console.log("PATEERN: " + simonGame.PATTERN + "COUNT " + simonGame.COUNT );
//calling user input
console.log("calling user Input");
handler.userInput();
setTimeout(function(){
if(handler.repeatFlag === false){ //execute count gen only if repeat flag is false inside user INPUT
genPattern();
}
},simonGame.COUNT*2000);
//console.log("pattern check true, calling pattern gen");
//},simonGame.COUNT*5000); //c`enter code here`lose setTimeout
}, //close patternMatcher
} //close simonGame
var handler = {
countRepPlayer: 0,
repeatFlag: false,
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}, //close patternRepeatPlayer
effect: function(id){
var img = document.getElementById(id);
if(img !== null && id !== undefined){
$( img ).fadeIn(100).fadeOut(100).fadeIn(100);//fadeOut(200).fadeIn(200);
//debugger;
var audio = new Audio(simonGame.SOUND[id].file);
audio.play();
//console.log("id inside effect " + id)
}
},//close effect
countDisplay: function(){
document.getElementById("count").innerHTML = "Count: " + simonGame.COUNT;
}, //close countIncrease
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" user " + userPattern);
console.log(" pattern " + simonGame.PATTERN);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" WRONG USER INPUT ");
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
console.log("inside else " );
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once**.**
return ;
}
}
//reset the userPattern Array
if(userPattern.length === simonGame.PATTERN.length){
userPattern.length = 0;
}
}); //close click.
}
} //close handler
Yes, It will be called recursively, because you set interval for it.
Here you can modify your code:
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}
To: (EDITED)
function myCallbackFunction(repeater){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
simonGame.patternMatcher();
handler.countRepPlayer = 0;
}
}
patternRepeatPlayer: function(){
var repeater = setInterval(function() {myCallbackFunction(repeater);}, 1000);
}
And where you need to call it once, just call myCallbackFunction(repeater)

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

Remove "NaN" from HTML document

It's a stupid thing tho be honest. As you see in my fiddle, you can add and remove fields. The sum of the total of the amount inserted in the input fields works well.
But when I remove a field (which the total is 0), it changes to NaN.
Is it possible to make NaN == 0?
http://jsfiddle.net/1ggaco1d/4/
$(document).ready(function () {
/* --- ADD FIELD --- */
rebind();
$('.TotalMultiField').each(function () {
var $wrapper = $('.multiFields', this);
$(".addField", $(this)).click(function (e) {
$('.multiField:first-child', $wrapper).clone(true)
.appendTo($wrapper)
.find('input')
.val('').focus();
rebind();
});
/* --- REMOVE FIELD --- */
$('.multiField .removeField', $wrapper).click(function () {
if ($('.multiField', $wrapper).length > 1) {
$(this).parent('.multiField').remove();
total();
}
});
});
});
function rebind() {
$(".number").on('blur', function(e) { total(); })
}
function total() {
var total = 0;
$(".number").each(function (idx, el) {
var value = $(el).val();
if (value !== "") {
total = total + parseFloat($(el).val());
}
});
$("#added").text(total);
}
You could use javascript isNaN() function.
like
if(isNaN(total) == ture)
{
total = 0;
}

How to show two numbers in jQuery?

Can you please tell me how to show number all time.
Given : LastNumber
when **previous** button click .
Result: 10 11
Result: 9 10
Result: 8 9
if user click next button
Result: 9 10
Result: 10 11
http://jsfiddle.net/LyXLD/3/
function printdown(count) {
$("#pre").html('')
$("#pre").html($("#curr").html());
$("#curr").html('')
$("#curr").html(count);
// $("#pre").html(count);
}
$("#next").click(function () {
if (++file_show_counter <= lastestCountValue) {
printdown(file_show_counter);
} else {
file_show_counter--;
}
});
Use this:
$(document).ready(function () {
$('#previos').click(function () {
var prevVal = parseInt($('#pre').html());
var curVal = parseInt($('#curr').html());
$('#pre').text(prevVal - 1);
$('#curr').text(curVal - 1);
});
$('#next').click(function () {
var prevVal = parseInt($('#pre').html());
var curVal = parseInt($('#curr').html());
if (curVal < 11) {
$('#pre').text(prevVal + 1);
$('#curr').text(curVal + 1);
}
});
});
Demo:http://jsfiddle.net/LyXLD/5/
i have 11 pages.and i have to show 2 pages at one time.i just know how
many pages i have mean (11). when i go up it show 9 and 10 page.then 8
and 9 page
Update
Well now that OP has actually stated this requirement, here's an updated solution.
Prev button stops working when it gets down to 1, and the next button stops working when it reaches the page count.
DEMO
var pageCount = 11;
$("#previous").on("click", function () {
$pre = $("#pre");
$curr = $("#curr");
$count = +$pre.text();
if ($count > 1) {
$pre.text($count - 1);
$curr.text($count);
}
});
$("#next").on("click", function () {
$pre = $("#pre");
$curr = $("#curr");
$count = +$curr.text();
if ($count < pageCount) {
$pre.text($count);
$curr.text($count + 1);
}
});
I just write new code please check it on http://jsfiddle.net/shantanubhaware/LyXLD/10/
working code
var lastval = $('#curr').text();
var preval = $('#pre').text();
var i = 0;
$('#previos').click(function () {
var lastval = $('#curr').text();
var preval = $('#pre').text();
previous();
});
$('#next').click(function () {
var lastval = $('#curr').text();
var preval = $('#pre').text();
next();
});
function previous() {
if (preval >= 1) {
--lastval;
--preval;
$('#curr').text(lastval);
$('#pre').text(preval);
}
}
Please take a look. Is that what you are looking for?
JSFIDDLE DEMO
var lastestCountValue = 11,
file_show_counter = lastestCountValue - 1;
$(document).ready(function () {
$("#previos").click(function () {
if (file_show_counter > 1) {
print(--file_show_counter, file_show_counter + 1);
}
});
$("#next").click(function () {
if (file_show_counter < lastestCountValue - 1) {
print(++file_show_counter, file_show_counter + 1);
}
});
});
function print(pre, cur) {
$("#pre").html(pre);
$("#curr").html(cur);
}

Categories

Resources