I'm having trouble figuring out why my JavaScript is not working right. Its with j Query and its supposed to select all the text area tags and then for each text area count the number of characters typed in them and then not allow the user to enter any more after it hits the max length, also showing a character counter under each text area box. What its doing is only showing the characters remaining but not decrementing after each key pressed and also not stopping when it hits the max length. It also doesn't select all of the text areas, it only takes the first one it finds.
Here is my TextAreaCounter.js
$(document).ready(function){
var $texts = $('textarea[maxlength]');
$texts.each(function){
$var $this = $(this),
max = $(this).attr('maxlength'),
textId = $(this)attr.('id'),
$parent = $this.parent(),
countId = textId+'-count';
$div = $('<div>Characters Remaining: </div>').addClass('count-down').insertAfter($this);
$input = $('<input></input>').attr({
type:"text",
readOnly: "readOnly",
value: max,
id: countId
}).css({
width: "25px"
marginTop: "5px"
marginBottom: "10px"
}).addClass('readOnly').appendTo($div);
$this.on({
keyup: function(){
val = $this.val(),
countVal = $('#'+countId).val(),
if(val.length > max){
$this.val(val.substr(0,max));
alert('Max length exceeded: ' +max);
return false;
}else{
$('#'+countId).val(max-val.length);
}
},
blur: function(){
val=$this.val();
if(val.length > max){
$this.val(val.substr(0,max));
alert('Max length exceeded: ' +max);
return false;
}else{
$('#'+countId).val(max-val.length);
}
}
});
});
});
When i added some alerts, not shown in the code here, it showed that it was not getting to the this.on section with the keyup event. I included this external js file to a jsp file which my page is made and has my text areas in. I also add an id and maxlength attribute to the textarea element. Any help would be great thank you.