Creating Stars rating system and I want to access the rating number and perform an action based on that. How can I access the number variable outside my click function?
$(document).ready(function () {
$(".li").mouseover(function () {
var current = $(this);
$(".li").each(function (index) {
$(this).addClass("hovered-stars");
if (index == current.index()) {
return false;
}
})
})
$(".li").mouseleave(function () {
$(this).removeClass("hovered-stars");
})
$(".li").click(function () {
$(".li").removeClass("clicked");
$(".hovered-stars").addClass("clicked");
var number = $(".clicked").length;
$("#message").html("You rated " + number + " Stars");
})
console.log(number);
})
Currently cannot print number variable outside click event listener
you need to declare the number variable outside the click function and then re-assign the value inside click function
$(document).ready(function () {
var number=0;
$(".li").mouseover(function () {
var current = $(this);
$(".li").each(function (index) {
$(this).addClass("hovered-stars");
if (index == current.index()) {
return false;
}
})
})
$(".li").mouseleave(function () {
$(this).removeClass("hovered-stars");
})
$(".li").click(function () {
$(".li").removeClass("clicked");
$(".hovered-stars").addClass("clicked");
number = $(".clicked").length;
$("#message").html("You rated " + number + " Stars");
})
console.log(number);
})
Related
I have a voting based system using javascript and local storage to save the designs & votes. I'd like a way to replace the design with the least amount of votes.
Currently I'm prepending a clone of the design to the start of the DOM, which obviously pushes the votes out of order and leaves me with more than 6 designs in the gallery.
Also I'm not sure of the logic if two designs have the same amount of votes?
Any hep would be appreciated.
Codepen here: https://codepen.io/fuzzyduck/pen/jOpzwXp
//variables for tracking votes
let voteVal1 = Number(localStorage.getItem("voteVal1"))
let voteVal2 = Number(localStorage.getItem("voteVal2"))
let voteVal3 = Number(localStorage.getItem("voteVal3"))
let voteVal4 = Number(localStorage.getItem("voteVal4"))
let voteVal5 = Number(localStorage.getItem("voteVal5"))
let voteVal6 = Number(localStorage.getItem("voteVal6"))
//log votes on load
console.log("Votes for 1: " +voteVal1)
console.log("Votes for 2: " +voteVal2)
console.log("Votes for 3: " +voteVal3)
console.log("Votes for 4: " +voteVal4)
console.log("Votes for 5: " +voteVal5)
console.log("Votes for 6: " +voteVal6)
//display votes on load
$(".voteVal1").html(voteVal1)
$(".voteVal2").html(voteVal2)
$(".voteVal3").html(voteVal3)
$(".voteVal4").html(voteVal4)
$(".voteVal5").html(voteVal5)
$(".voteVal6").html(voteVal6)
//increase votes
$(".btn1").on("click", function () {
localStorage.setItem("voteVal1", ++voteVal1)
$(".voteVal1").html(voteVal1)
})
$(".btn2").on("click", function () {
localStorage.setItem("voteVal2", ++voteVal2)
$(".voteVal2").html(voteVal2)
})
$(".btn3").on("click", function () {
localStorage.setItem("voteVal3", ++voteVal3)
$(".voteVal3").html(voteVal3)
})
$(".btn4").on("click", function () {
localStorage.setItem("voteVal4", ++voteVal4)
$(".voteVal4").html(voteVal4)
})
$(".btn5").on("click", function () {
localStorage.setItem("voteVal5", ++voteVal5)
$(".voteVal5").html(voteVal5)
})
$(".btn6").on("click", function () {
localStorage.setItem("voteVal6", ++voteVal6)
$(".voteVal6").html(voteVal6)
})
$(".resetAllVotes").on("click", function () {
localStorage.setItem("voteVal1", 0)
$(".voteVal1").html(0)
localStorage.setItem("voteVal2", 0)
$(".voteVal2").html(0)
localStorage.setItem("voteVal3", 0)
$(".voteVal3").html(0)
localStorage.setItem("voteVal4", 0)
$(".voteVal4").html(0)
localStorage.setItem("voteVal5", 0)
$(".voteVal5").html(0)
localStorage.setItem("voteVal6", 0)
$(".voteVal6").html(0)
})
//set colours on load
$(".container div").each(function(index) {
$(this).removeClass().addClass(localStorage.getItem(String(index))).addClass("circle")
})
//change colours
$(".btnred").on("click", function () {
$("#main").removeClass().addClass("red")
localStorage.setItem('ClassName', 'red')
})
$(".btnblue").on("click", function () {
$("#main").removeClass().addClass("blue")
localStorage.setItem('ClassName', 'blue')
})
$(".btnpurple").on("click", function () {
$("#main").removeClass().addClass("purple")
localStorage.setItem('ClassName', 'purple')
})
$(".clone").on("click", function () {
//the below has already been created in v1 - this is just for testing
$("#main").clone().removeClass("main").prependTo(".container")
$(".container div").each(function(index) {
localStorage.setItem(index, this.className)
})
//remove design with least votes (this is where the fun begins)
voting();
})
function voting(){
//new design will currently pre-pend to top left - but it should replace the design with the lowest score
//we then need to reset the voteVal to zero on the new design
//check which the lowest score (what if they have the same score?)
let pos1Check = [voteVal2,voteVal3,voteVal4,voteVal5,voteVal6];
if(voteVal1 > Math.min.apply(null, pos1Check)) {
console.log("Pos1: higher");
} else {
console.log("Pos1: lower");
}
//if pos2 fails we can remove it as it likely to have to least votes
let pos2Check = [voteVal1,voteVal3,voteVal4,voteVal5,voteVal6];
if(voteVal2 > Math.min.apply(null, pos2Check)) {
console.log("Pos2: higher");
} else {
console.log("Pos2: lower");
}
let pos3Check = [voteVal1,voteVal2,voteVal4,voteVal5,voteVal6];
if(voteVal3 > Math.min.apply(null, pos3Check)) {
console.log("Pos3: higher");
} else {
console.log("Pos3: lower");
}
let pos4Check = [voteVal1,voteVal2,voteVal3,voteVal5,voteVal6];
if(voteVal4 > Math.min.apply(null, pos4Check)) {
console.log("Pos4: higher");
} else {
console.log("Pos4: lower");
}
let pos5Check = [voteVal1,voteVal2,voteVal3,voteVal4,voteVal6];
if(voteVal5 > Math.min.apply(null, pos5Check)) {
console.log("Pos5: higher");
} else {
console.log("Pos5: lower");
}
let pos6Check = [voteVal1,voteVal2,voteVal3,voteVal4,voteVal5];
if(voteVal6 > Math.min.apply(null, pos6Check)) {
console.log("Pos6: higher");
} else {
console.log("Pos6: lower");
}
}
I current have a class in Javascript to handle a cart (only with static data as it stands). However, when I try to add two integers together:
var Cart = {
handler: {
totalCost: 0,
addCost: function() {
$('#cart li').each(function() {
var cost = +$(this).attr('cost');
console.log('single cost: ' + cost);
var total = this.totalCost + cost;
console.log('after add: ' + total);
});
console.log(this.totalCost);
}
}
};
I get this output:
after add: NaN
I have tried ensuring both values are numerical adding a + delimiter to the variable, I receive the same output? A sample of working code is at JsFiddle.
You have a scoping issue - within the each function this no longer refers to handler, but to the currently iterated element. You can fix this by referring directly to Cart.handler:
$(document).ready(function() {
var Cart = {
handler: {
productId: 'pid-',
totalCost: 0,
yesNoAlert: $('.display'),
addCost: function() {
$('#cart li').each(function() {
cost = +$(this).attr('cost');
console.log('single cost: ' + cost);
total = Cart.handler.totalCost + cost;
console.log('after add: ' + total);
});
console.log(Cart.handler.totalCost);
},
removeProduct: function(pid) {
this.productId = pid;
this.displayYesNo('remove');
},
displayYesNo: function(callback) {
this.yesNoAlert.attr('callback', callback);
this.yesNoAlert.slideToggle('slow');
},
callback: function(callback) {
if (callback === 'remove') {
$('#' + this.productId).hide();
}
this.yesNoAlert.hide();
},
throw: function(e) {
$('#error').html(e);
$('#error').slideToggle('slow');
}
}
};
https://jsfiddle.net/d6kccr88/3/
you can save the value of this in another variable that and use that variable in your method to save the this value
because in jquery each method the value of this will be your currect element which are currently iterating
I wrote a little filter to click 3 different lvl 1 filter and 3 different lvl 2 filters. On every click at one filter it should show the result of each filter. But after clicking a few times, the browser starts getting slower and slower. I put an alert in it and found out, that everytime i click an filter the function runs 2 times -> 4 times -> 8 times -> 16 times. So if I click maybe 30 times the filter, the browser collapse.
Pls. help
Greetings Max
var fil1 = "";
var fil2 = "";
var filcomp = "";
$(function func() {
/*Filter 1*/
$("#Filter_btn_1").click(function () {
fil1 = ".filter_option1";
filter();
});
$("#Filter_btn_2").click(function () {
fil1 = ".filter_option2";
filter();
});
$("#Filter_btn_3").click(function () {
fil1 = ".filter_option3";
filter();
});
/*Filter 2*/
$("#Filter_btn_4").click(function () {
fil2 = ".filter_option4";
filter();
});
$("#Filter_btn_5").click(function () {
fil2 = ".filter_option5";
filter();
});
$("#Filter_btn_6").click(function () {
fil2 = ".filter_option6";
filter();
});
filcomp = fil1 + fil2;
$('.filter_btn').click(function () {
$(".filter_btn").removeClass("filter_selected");
$(this).addClass("filter_selected");
});
$('.filter_btn2').click(function () {
$(".filter_btn2").removeClass("filter_selected");
$(this).addClass("filter_selected");
});
$('.filter_reset_btn').click(function () {
location.reload();
});
function filter() {
alert(filcomp);
func();
$(".post").hide();
$("div").filter(filcomp).show();
};
});
i usesd
var counter =0;
if(counter==0){
function filter() {
counter = 1;
func();
$(".career_post").hide();
$("div").filter(filcomp).show();
return counter;
};
};
I have this working JS which checks if different checkboxes are or not checked and asigns a different price for each one that will later be summed up.
function priceCandy1() {
var priceCandy1 = 0;
var candy = document.getElementById("candy1");
if(candy.checked==true)
{
priceCandy1=13;
}
return priceCandy1;
}
function calculateTotal()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
document.getElementById('totalid').innerHTML = "$" + totalPrice;
}
Now I'm trying to code the equivalent in jQuery and this function does work:
$(function () {
var priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
return priceCandy1;
});
But I can't grab the returned price into a function that will add up every priceCandy#. Out of scope but I donĀ“t know how to fix it.
If it is an issue of scope like you say, you could declare priceCandy1 outside the function, as a global variable.
var priceCandy1;
$(function () {
priceCandy1 = 0;
var candy = $('#candy1');
$('#candy1').on('click',function () {
if (candy.is(':checked')) {
priceCandy1 = 13;
}
});
});
Then use priceCandy1 in your totalPrice function and it should be able to fetch it.
Wrap them in the same function:
$(function () {
var priceCandy1 = function() {
if($('#candy1').is(':checked')) {
return 13;
}
return 0;
},
calculateTotal = function()
{
var totalPrice = priceCandy1() + priceCandy2() + priceCandy3();
$('#totalid').text('$' + totalPrice);
};
calculateTotal();
});
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;
}