Reputation: 5525
I want to count how many characters inside textarea (if any) when the page is loaded on the screen for the first time. then I also want to show it when user add more characters or delete some of it.
My HTML Code :
<form>
<div class="form-group">
<textarea id="textBox" class="form-control" rows="10">Hello world</textarea>
<div id="charNum"></div>
</div>
</form>
and I have this jQuery script :
function countChar() {
var len = val.value.length;
$('#charNum').text(len+' characters');
};
$(document).ready(function(){
countChar();
$('#textBox').change(countChar);
$('#textBox').keyup(countChar);
});
but it's not displaying result as I wanted, what did I do wrong here?
Upvotes: 0
Views: 1388
Reputation: 171669
Here's another version that allows using this
inside countChar()
function countChar() {
// since only used as event handler callback reference have access to `this`
var len = this.value.length;
$('#charNum').text(len + ' characters');
};
$(document).ready(function () {
// trigger event on page load to set first count
$('#textBox').change(countChar).change();
$('#textBox').keyup(countChar);
/* or combine both events and trigger one of them on page load */
$('#textBox').on('change keyup', countChar).change();
});
Since the function is only ever used as a reference for event handler it will automatically expose this
as the element instance
Upvotes: 0
Reputation: 388316
There are 2 problems in your script
'
function countChar() {
var len = $('#textBox').val().length;
$('#charNum').text(len + ' characters');
};
$(document).ready(function() {
countChar();
$('#textBox').change(countChar);
$('#textBox').keyup(countChar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div class="form-group">
<textarea id="textBox" class="form-control" rows="10">Hello world</textarea>
<div id="charNum"></div>
</div>
</form>
Upvotes: 3