Harshitha Kumar Harshitha Kumar - 1 month ago 8
Javascript Question

Javascript for validating Multiline Text area's input characters

I have a multiline text area which accepts 42 characters and if the user exceeds the limit and clicks on submit button, he will get a alert message like 'exceeded the limit so remove '***' characters. Below is the code which performs the same.

<head runat="server">
<title></title>
<script type="text/javascript">
function ok(maxchars) {
if (document.ourform.box.value.length > maxchars) {
alert('Too much data in the text box! Please remove ' +
(document.ourform.box.value.length - maxchars) + ' characters');
return false;
}
else
return true;
}
</script>
</head>
<body>
<div>
<form action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/chkarea.pl"
method="post" name="ourform" onsubmit="return ok(42)">
Please enter data, at most 42 characters:<br/>
<textarea name="box" rows="5" cols="30">
</textarea>
<br/><input type="submit"/>
</form>
</div>
</body>
</html>


But my problem is I should get the same alert message once I de-focus the control from the text box area instead of clicking on submit button.
So Please help me for achieving it...!!
Thanks in advance...

Additional requirement: After getting the alert message and clicking on ok button,the extra characters should be deleted. Please help..

Answer

Here is a simple solution using jQuery

$(function(){
	$("#box").keypress(function(){
  	if($(this).val().length > $(this).data("limit") - 1) {
			alert("You have reached the limit");
  		return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="ourform">
  Please enter data, at most 42 characters:<br/>
  <textarea name="box" rows="5" cols="30" data-limit="10" id="box">
  </textarea>
  <br/><input type="submit"/>
</form>

Please try this.