0

I have the html

<span class="offersReceivedCount">3</span>

and I want to run code when the 3 value changes to something else. I'm using handlebars so the real html looks like

<span class="offersReceivedCount">{{offers}}</span> Offers Received</p>

I tried

$(".offersReceivedCount").change(function(){
console.log("change");
});

But this never logs anything when the value of {{offers}} changes

Do I need a different event type or maybe try different approach?

epascarello
  • 204,599
  • 20
  • 195
  • 236
chackerian
  • 1,301
  • 2
  • 15
  • 29

2 Answers2

2

What you need is a ReactiveVar and define an equality function on that.

Template['your-template'].onCreated = function() {
   this['offerReact'] = new ReactiveVar(this['offers'], function(oldValue, newValue) {
       if (oldValue !== newValue) {
           // run the function you want to trigger when value change 
           return false;
       } else {
           // no change, do nothing, just return true;
           return true;
       }

   });
}

So, whenever you set the new value to the offerReact, the equal function will be triggered and then start to run the event you want to run

Thai Tran
  • 9,815
  • 7
  • 43
  • 64
1

A different approach (I don't know how well it would work for you) would be to make an input "look" like a span tag, see fiddle: https://jsfiddle.net/f1a990f1/

Then your code will work sense the change function does not work with the span tag.

HTML

<input class="offersReceivedCount" type="text" value="333">
<script>
  $(".offersReceivedCount").change(function() {
    alert("change");
  });

</script>

CSS

input {
  border: none;
  outline: none;
  background-color: transparent;
  font-family: inherit;
  font-size: inherit;
}
Adam Buchanan Smith
  • 9,422
  • 5
  • 19
  • 39