0

I have a working javascript function checking the character count in a TextBox of a webform, being called with onChange. The alert notifies the user of the character limit and the current character count, so the inclination is to reduce the number of characters after clicking ok on the alert. However, onChange will not function at this point.

I would like suggestions on how my function can be called continuously while the character count remains over the limit (and the user increments downwards based upon the character count feedback.

My function:

<script type="text/javascript">
function CountDesc(text,long)
{
    var maxlength = new Number(long); 
    var count = text.value.length;
    if (count  > maxlength){
    text.value = text.value.substring(0,maxlength);alert("Incident Description may 
        only contain " + long + " characters.\nCurrent character count is: " + count);
    }
}

My function Call:

<asp:TextBox ID="txtDescription" runat="server" Height="80px" TextMode="MultiLine"
Width="680px" MaxLength="1000" TabIndex="33" onChange="CountDesc(this,1000)"></asp:TextBox>

Thanks.

  • See http://stackoverflow.com/questions/451491/what-is-the-best-way-to-emulate-an-html-input-maxlength-attribute-on-an-html-t, http://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript and http://stackoverflow.com/questions/10468680/how-to-limit-number-of-characters-in-a-textarea-field-processing-php – Nivas Mar 31 '14 at 13:20
  • @Nivas Good response - and exceedingly quick, may I add. Found what I needed - along with several alternatives. Thanks – jdwired Mar 31 '14 at 14:01

1 Answers1

0

You can totally use HTML5 for this.

Keep in mind that you don't need to support older browsers perse. You should check the character count server-side anyway. If the character count exceeds the specified length throw an error message there. The in-form check is nice-to-have but not essential.


Usually alert is not a very good user experience. The user can not continue unless he deals with the popup and JavaScript blocks as well - potentially breaking other things on the page.

You could add an error message near the textarea that indicates you are over the limit. This is a much less intrusive way of informing the user of an input problem. Again, you should check your input server side anyway. If the user chooses to ignore the message, well, that's his choice but you're still not going to accept the input.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Thanks for the reply. It's client requirements - client-side validation, and alerts. I settled on my onChange, and onKeyPress="return(this.value.length < 1000);" Between the two, i think they'll be happy enough. – jdwired Mar 31 '14 at 14:49