Reputation: 998
I have a number within a span element that changes often. I want to be able to detect any changes in this number and store that number in a variable.
so far I have tried this:
var x = $('#mynum').text();
This code however doesn't detect any changes - it only gets the value when the page first loads.
I have also tried this:
$('#mynum').bind('change',function(){
alert('wahoo!'); });
However I cannot get it to even make the alert.
What would be the best way to detect the changes and store the number in a variable whenever it does change?
Upvotes: 3
Views: 8202
Reputation: 77986
Change event only happens from the browser on the blurring of form fields. If you're changing the value of a span from your script, you need to $('#mynum').trigger('change');
. Then your bind will work, assuming the element #mynum
was in the DOM when the bind was set. If not, bind to a consistent parent element and delegate it with on
:
$('#myParentNode').on('change','#mynum', function() {
alert('wahooo!');
});
Upvotes: 5