Today, we would like to demonstrate how to limit the number of characters in a textarea field in JavaScript.
Let’s take a look at the code that makes this solution possible:
<style>
.x{
background:lightblue;
font-weight:bold;
font-size:20pt;
padding:0px 10px;
}
.y{
font-family:arial black;
color:red;
}
</style>
<script>
function limitText(v){
len = v.length;
var s = document.testForm.Msg.value;
c = 10 - len;
if(len > 10){
m = s.substr(0,10);
document.testForm.Msg.value = m;
c = 0;
}
document.testForm.count.value = c;
}
</script>
<form name='testForm'>
<textarea cols='35' rows='6' name='Msg' class='y' onkeyup="javascritp:limitText(this.value);"></textarea>
<input type='button' class='x' name='count' value='10' />
</form>
The code provided is a simple and effective solution for this requirement. The use of JavaScript in combination with HTML and CSS allows for a dynamic and user-friendly interface. By setting a maximum character limit for the textarea, it ensures that the input remains concise and consistent.
The “limitText” function, which is called by the onkeyup event of the textarea, takes the value of the textarea and determines its length. If the length is greater than 10 characters, the first 10 characters are selected and set as the new value of the textarea, while the character counter button is updated accordingly.
The styling section, using CSS classes, sets the appearance of the button and textarea, giving the interface a more polished and professional look. The use of CSS makes it easy to adjust the appearance and layout, allowing for customization to meet specific requirements.
At Invezza, we understand the importance of efficient and user-friendly interfaces. This code provides a simple solution for limiting textarea characters, and we are experts in providing custom JavaScript solutions for a variety of needs. If you have any questions or need assistance with a similar project, please don’t hesitate to reach out to our team of experts.