Reputation: 22760
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 :-/
Upvotes: 0
Views: 25
Reputation:
$('#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.
Upvotes: 2