Javascript records the number of text in the text box to detect the number of text changes

  • 2020-03-30 04:07:32
  • OfStack

Recently, I encountered such a problem in a project. I had to count the text entered by the user in the text box, which is shown below. Because we are a short message sending platform, now our country's short message service, if your message is more than 70 characters, the message will be sent to you in two messages. So we were asked to show the user how many words he typed. So that the user knows how many pieces of information I will give.

In the net a code, put up, began to use, ok, good, but after a period of use found a problem. Is after you delete the word, the above word count change has a problem, later studied, find the problem. OnKeyDown ="showLen(this)" onKeyUp="showLen(this) "used to use one of these methods at a time, and none of them were used, and both of them count when you press the keyboard and when you release the keyboard, okay, I'll put the program up


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD> 
<TITLE> New Document </TITLE> 
<META NAME="Generator" CONTENT="EditPlus"> 
<META NAME="Author" CONTENT=""> 
<META NAME="Keywords" CONTENT=""> 
<META NAME="Description" CONTENT=""> 
<mce:script language="javascript"><!-- 
function showLen(obj) 
{ 
document.getElementById("contentLen").value=obj.value.length; 
document.getElementById("smsnum").value=Math.floor(obj.value.length/70)+1; 
} 
// --></mce:script> 
</HEAD> 
<BODY> 

<textarea name="content" cols="60" rows="5" id="content" onKeyDown="showLen(this)" onKeyUp="showLen(this)">

Related articles: