Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  125] [ 1]  / answers: 1 / hits: 139512  / 15 Years ago, wed, august 19, 2009, 12:00:00

I'm trying to implement a generic function for a form with several fields in the following format.



<label id=LblTextCount></label>
<textarea name=text onKeyPress=checkLength(this, 512, LblTextCount)>
</textarea>


And the following JavaScript:



function checkLength(object, maxlength, label) {
charsleft = (maxlength - object.value.length);

// never allow to exceed the specified limit
if( charsleft < 0 ) {
object.value = object.value.substring(0, maxlength-1);
}

// I'm trying to set the value of charsleft into the label
label.innerText = charsleft;
document.getElementById('LblTextCount').InnerHTML = charsleft;
}


The first part works fine, but I'm not able to set the charsleftvalue into the label. What am I doing wrong?
Please note that I'm looking for a dynamic approach instead of hard coding the label name into the JS function. JQuery would be fine too :)





Solution - thanks to all!



HTML



<label id=LblTextCount></label>
<textarea name=text>
</textarea>


JS



$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});

function checkLength(obj, maxlength, label) {
var charsleft = (maxlength - obj.val().length);

// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}

// set the value of charsleft into the label
$(label).html(charsleft);
}

More From » javascript

 Answers
19

InnerHTML should be innerHTML:



document.getElementById('LblAboutMeCount').innerHTML = charsleft;


You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:



$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});


You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:



function checkLength(obj, maxlength, label) {
charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// I'm trying to set the value of charsleft into the label
label.text(charsleft);
$('#LblAboutMeCount').html(charsleft);
}


So if you apply the above, you can change your markup to:



<textarea name=text></textarea>

[#98880] Friday, August 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;