Friday, 5 September 2014

How to set maximum characters in textbox

Hi Guys,

In this post,  we are going to learn how to set  limit the maximum number of characters in textbox and we count the number of characters entered in textbox .




Add this jquery code in your page

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
   
    function CountCharacters(txtMsg, CharLength, indicator) {
        chars = txtMsg.value.length;
        document.getElementById('lblcountEnter').innerHTML = chars;
        document.getElementById(indicator).innerHTML = CharLength - chars;
        if (chars > CharLength) {
            txtMsg.value = txtMsg.value.substring(0, CharLength);
        }
    }
</script>


And also paste this html code in your page 


<div>
    Number of Characters Left:
    <label id="lblcount"<br />
    Number of Characters You Have Enter:
    <label id="lblcountEnter">140</label><br />
   
    <textarea id="mytextbox" rows="5" cols="25" onkeyup="CountCharacters(this,139,'lblcount');"></textarea>
</div>


We can also set maxlength in textbox also like .

<input type="text" name="usrname" maxlength="10">



Happy coding



No comments:

Post a Comment