Reputation: 780
I'm trying to limit the max characters in a textarea, using JS, i leave here my HTML & JS code:
HTML-->
<form id="formu" action="ok.html" method="post" enctype="multipart/form-data">
<p>
<label for="observaciones">Observaciones:</label>
<textarea id="observaciones" cols="30" rows="5"></textarea>
</p>
</form>
JS-->
window.onload=function(){
document.getElementById("observaciones").addEventListener('keypress',function(){maxlong(document.getElementById("observaciones")),150},false);
}
function maxlong(obj,maxlength){
return(obj.value.length<=maxlength);
}
Upvotes: 0
Views: 141
Reputation: 780
Solved doing this:
function maxlong(elEvento){
var evento=elEvento||window.event;
var obser=document.getElementById("observaciones").value;
if(obser.length>=15){
evento.preventDefault();
}
}
And also i had an extra "{" that made the program not working well...
Upvotes: 0
Reputation: 3559
This is basic to set maxlength:
<textarea maxlength="50">
Enter text here...
</textarea>
Upvotes: 0
Reputation: 2303
<script>
function maxLength(obj){
if(obj.value.length <=150){
return true;
}else{
return false;
}
}
</script>
<textarea onkeypress="return maxLength(this);"></textarea>
Upvotes: 0
Reputation: 6992
your event handler doesn't actually do anything. You need to prevent the default beahviour of the event (with the preventDefault method on the event object).
Upvotes: 1
Reputation: 1115
try this:
function limiter() {
var area = document.getElementById("content_txt");
var message = document.getElementById("message");
var maxLength = 160;
var checkLength = function () {
if (area.value.length <= maxLength) {
message.innerHTML = (maxLength - area.value.length) + " characters remainging";
}
}
setInterval(checkLength, 300);
}
and this is the textarea
<textarea style="resize:none; margin-bottom: 0px;" id="content_txt"
name="TextArea1" runat="server"
maxlength="160" onkeyup="return limiter();" ></textarea>
Upvotes: 0