SoMeGoD SoMeGoD - 3 months ago 9
jQuery Question

Check if any of the duplicated class have text equals or higher then 21

I'm trying to setup a discount monitor over my e-commerce to check if someone publishes products with wrong discount. My product page have about 30 items and some of them have a little discount label like this:

<span class="nf-off-price"><b>20</b>% off!</span>
<span class="nf-off-price"><b>7</b>% off!</span>
<span class="nf-off-price"><b>12</b>% off!</span>
<span class="nf-off-price"><b>5</b>% off!</span>
<span class="nf-off-price"><b>4</b>% off!</span>
<span class="nf-off-price"><b>4</b>% off!</span>


I need to check if any of those labels have a 'nf-off-price > b' equals or higher then 21, and if so, issue an chrome alert. I was able to achieve that but only when setting a solid number, like this:

if(Notification.permission !== 'granted'){Notification.requestPermission();}

var check = function(){
if ($('.nf-off-price:contains("21")').length > 0) {
n = new Notification( "Discount Alert", {
body: "A possible discount typo was found",
icon : "http://cloudcheckr.com/wp-content/uploads/2015/12/alert.jpg"
});
}
};
setTimeout(check, 5000); // Do not remove. The code needs to fire 5 seconds after page load


I understand that my code will look for a label with exactly 21 and that's the problem. How can I do for the code to check if at least one out of the many ".nf-off-price" on the page contains equals or higher then 21?

Answer

Modify your check function to this:

var check = function(){
    $('.nf-off-price b').each(function() {
      if (parseInt(this.innerHTML, 10) > 20) {
         n = new Notification( "Discount Alert", {
             body: "A possible discount typo was found",
             icon : "http://cloudcheckr.com/wp-content/uploads/2015/12/alert.jpg"
         });
         return;
      }
    })
};