Jesper Møller
Jesper Møller

Reputation: 137

multiple calculation with different prices

I have made a small script to calculate the numbers and price on a orderform. How ever i need some help to figure out how to calculate the difrent prices on the difrent objects and the number of eatch obejects

My script look like this now

 function calculateSum() {
  var antal = 0;
  var sub = 0;
  var price = 30;
  $(".mad" && ".mad2").each(function() {
  //add only if the value is number
  if (!isNaN(this.value) && this.value.length != 0) {
  antal += parseFloat(this.value);
  sub = antal * price;
  $(this).css("background-color", "#ffffff");
  }
  else if (this.value.length != 0){
  $(this).css("background-color", "#e68d8d");
  }
  });
  $("#antalrug").html(antal.toFixed(0));
  $("#subtotal").html(sub.toFixed(0));
 }

so far so god, however i need the price to be flexible so that if its ".mad" its 30 and if its .mad2 its 35 ! How do i set it up so the calculation depends on witch class the function is looking on ?

Somthing like:

if (this = "mad2") {
      price = 35; 
  }
else {
      price = 30;
      $(

I simply cant get it to work i have tryde both sugestion my script now looks like this

    $(".mad, .mad2, .mad3, .mad4, .mad5, .mad6").each(function() {
        //add only if the value is number
        if (this.value.trim().length != 0 && !isNaN(this.value.trim()) ) {
        //Set max to 25
        if (this.value >= 25){
        this.value= 25
        }
        if($(this).hasClass("mad2")){
            price = 35;
            }
        else{
            price = 30;
            }
            antal += parseFloat(this.value);
            subtotal = antal*price;
            $(this).css("background-color", "#ffffff");
        }
        else if (this.value.length != 0){
             $(this).css("background-color", "#e89898");
        }
    });

buth now all prices are 35 ??

Upvotes: 0

Views: 181

Answers (2)

fu8ar
fu8ar

Reputation: 150

Why not give both selectors .mad1 and mad2 an additional class and then you can do this:

$(".newClass").each(function() {

    if($(this).hasClass("mad1")){
        price = 30;
    }
    else{
        price = 35;
    }
}

Upvotes: 0

Radek Pech
Radek Pech

Reputation: 3098

inside the each function

if ($(this).is('.mad')) {
    price = 30;
} else {
    price = 35;
}

Upvotes: 1

Related Questions