Question

I have a coupon system that whenever a new order detail is created it applies the coupon to the field labeled coupon_value. I'm trying to introduce the idea of a tiered coupon system and and trying to figure out if there is some way to figure ouch which instance of .each() you are on.

Here is my code:

//Default value of the coupon is $200
coupon_value = 200;

//If there are 5 students or more the coupon value is $300
teir_value = 300;

//For each coupon_value set its html to the coupon value variable
$('.coupon_value').each(function(){
    $(this).html('$' + coupon_value));
});

Here is the idea of what I'm trying to do:

Student 1 discount: $200 Student 2 discount: $200 Student 3 discount: $200 Student 4 discount: $200 Student 5 discount: $300 Student 6 discount: $300 ....

Is there someway I can say in the .each if this is the 5th or greater instance of the class coupon value on the render then either adjust coupon_value = $300 or just use tier_value?

Was it helpful?

Solution

You can use the index of the current item to check whether it is the 5th or more item. The each() callback gets the index of the current item and the current item as 2 arguments.

//Default value of the coupon is $200
coupon_value = 200;

//If there are 5 students or more the coupon value is $300
teir_value = 300;

//For each coupon_value set its html to the coupon value variable
$('.coupon_value').each(function (i) {
    $(this).html('$' + (i > 3 ? teir_value : coupon_value));
});

Demo: Fiddle

As you have used, if you want to refer to the current item in the loop you can use this inside the each handler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top