0

I have been trying to do this for hours, and it's persisted in not working. I can't find why.

My HTML:

<label>
Description<br>
(<span id='fieldLength'>0</span> Chars. ±1):

<textarea name='dataDescr' id='metaDescr'>Some Text Here.</textarea>
</label>

What I have that Does not work . It does not give me any response, no console errors in firebug or any sort of feedback :

JQuery:

counterChecker = function() {
    var max = 800;
    var lengthVal = $('#metaDescr').val().length;
    var fl = $('#fieldLength');
    if (lengthVal >= max) {
        var char = lengthVal - max;
        fl.text('Over by ' + char);
    }
    else {
        fl.text(lengthVal);
    }
}

$(document).ready(function() {
    $('#metaDescr').on("change", counterChecker() );
 });

Edit: This also does not work if the function is set out within the document ready brackets.

But what DOES work is the same code directly inserted into the on change function as an anonymous function:

 $(document).ready(function() {

    $('#metaDescr').on("change", function() {
        var max = 800;
        var lengthTwo = $(this).val().length;
        var lf = $('#fieldLength');
        if (lengthTwo >= max) {
            var char = lengthTwo - max;
            lf.text('Over by ' + char);
        }
        else {
            lf.text(lengthTwo);
        }
    });
});

Can someone help me understand why this difference?

Why doesn't it work as a separate called function and yet does not give any errors to my firebug, yet it can work as directly referenced (anonymous?) function . How can I make it behave as intended but keeping the code in a separate self contained functional unit.

I'm using JQuery 1.11.3 and viewing many stackoverflow posts over the last few hours hasn't shown the light :-/

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132

1 Answers1

2

$('#metaDescr').on("change", counterChecker() );calls the counterChecker function and assigns the returned value to the onchange handler. In this case it returns undefined and uses that as the change listener. What you want is $('#metaDescr').on("change", counterChecker); which passes a refrence to the counterChecker function that will be called when the change event fires.

  • That works, thank you! I can't believe I've been going round this for hours and all it was was a pair of empty brackets. Grrrr . – Martin Mar 08 '16 at 19:04
  • Don't beat yourself up it's a common mistake that is hard to debug. You will see it a lot on SO in regards to setTimeout & setInterval. –  Mar 08 '16 at 19:06
  • I suspect it comes as well from me using a lot of PHP whose functions are defined as such by being followed by brackets. Also without the brackets I thought Javascript/JQuery was asking for a `var`iable – Martin Mar 08 '16 at 19:08