1

I'm trying to create a free delivery banner if the price of a product is over £50.

My attempt:

$(function() {

if( $('.num').filter(function(index){
    return parseInt(this.innerHTML) > 50.00;})) {

    $(document.createElement('div')).attr('id', 'freeDelivery').appendTo('.imgoffer');
$('#freeDelivery').append('<img id="freeDeliveryImage" alt="Free delivery on this item" src="https://location_of_image.png" width="70" height="70">');

    }   
});

My code inserts the free delivery element even if the amount isn't over 'x'. Any suggestions?

Dan382
  • 976
  • 6
  • 22
  • 44
  • remember to always use radix: http://stackoverflow.com/questions/850341/how-do-i-work-around-javascripts-parseint-octal-behavior – Adam Zielinski Sep 27 '13 at 11:02

1 Answers1

3

.filter() returns a jQuery object(even if the collection is empty) and an object is a truthy value in JavaScript, you should read the .length property of the returned object.

if ( $('.num').filter(function() { return [condition] }).length ) {
    ... 
}

Also note that you should specify the radix for the .parseInt() method, otherwise you will get unexpected results.

parseInt(str, radix);
Ram
  • 143,282
  • 16
  • 168
  • 197