cup_of cup_of - 5 months ago 13
jQuery Question

how to change variable values using if statement in jQuery/jS

Hello I am having some trouble with my program. I've set some variables in the beginning of my program but Id like to change them with an if statement. Right now the first if statement gives me the results i want, but the second else if statement isnt working and the variables take the default values of '0'

here is the start of my jQuery code:

jQuery(".repair-grid-item1").click(function(){
jQuery(".repair-grid-item1 i").toggle();
jQuery(".repair-grid-item1").toggleClass("grid-active");
jQuery('.repair-grid-item1').gg();
});

(function( $ ){
$.fn.gg = function() {
var price = 0;

var one = 0;
var two = 0;
var three = 0;
var four = 0;
var five = 0;
var six = 0;

// *** this code block is working, returning correct values ***
if (jQuery(".repair-grid-item").hasClass("iPhone5")) {
var one = 85;
var two = 70;
var three = 75;
var four = 65;
var five = 75;
var six = 80;
}


// *** this code block isnt working, returning default values of 0 ***
else if (jQuery(".repair-grid-item").hasClass("iPhone5c")) {
var one = 85;
var two = 70;
var three = 75;
var four = 65;
var five = 75;
var six = 80;
}

//one only
if (jQuery(".repair-grid-item1").hasClass("grid-active") &&
!jQuery(".repair-grid-item2").hasClass("grid-active") &&
!jQuery(".repair-grid-item3").hasClass("grid-active") &&
!jQuery(".repair-grid-item4").hasClass("grid-active") &&
!jQuery(".repair-grid-item5").hasClass("grid-active") &&
!jQuery(".repair-grid-item6").hasClass("grid-active"))
{
price = one;
document.getElementById("total-price").innerHTML = price;
localStorage.setItem("sum", price);
}
};
})( jQuery );


here is a small snippet of my html code (this is the iPhone5 page)

<div class="repair-grid-item repair-grid-item1 iphone5">
<h3>Screen Repair</h3>
<i class="fa fa-check-circle-o fa-2x" aria-hidden="true"></i>
</div>


iphone5c page:

<div class="repair-grid-item repair-grid-item1 iphone5c">
<h3>Screen Repair</h3>
<i class="fa fa-check-circle-o fa-2x" aria-hidden="true"></i>
</div>


thanks!

Answer

The problem is that you are checking for the class iPhone5c instead of the class iphone5c, note the capital P. JQuery is case sensitive, so you should writte them in with the same caps.

So your your code is storing 0 on the variables because it doesn't pass the if else condition.

Furthermore, as other answers say, due to the scope, variables don't need to be redeclared using var inside the if. You should remove that.

Comments