Home  >  Article  >  Web Front-end  >  js implementation of text box input text number limit code_javascript skills

js implementation of text box input text number limit code_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:23:471432browse

Usually, the number of words entered in the text box is not unlimited. There is usually a maximum input limit. A more user-friendly website may have a countdown effect on the number of words that can be entered. For example, if there are 20 left, you can enter like this Tips, let’s use an example to introduce how to achieve this effect.

Look at the renderings first:

The code is as follows:

<html> 
<head> 
<title>文本框输入文字倒计效果代码</title> 
<style type="text/css"> 
* 
{ 
 margin:0; 
 padding:0; 
} 
.box 
{ 
 width:500px; 
 margin:10px auto; 
} 
p span 
{ 
 color:#069; 
 font-weight:bold; 
} 
textarea 
{ 
 width:300px; 
} 
.textColor 
{ 
 background-color:#0C9; 
} 
.grey 
{ 
 padding:5px; 
 color:#FFF; 
 background-color:#CCCCCC; 
} 
</style> 
<script type="text/javascript" src="jQuery/jquery-1.8.3.js"></script> 
<script type="text/javascript"> 
$(function(){ 
 var $tex=$(".tex"); 
 var $but=$(".but"); 
 var ie=jQuery.support.htmlSerialize; 
 var str=0; 
 var abcnum=0; 
 var maxNum=280; 
 var texts=0; 
 
 $tex.val(""); 
 $tex.focus(function(){ 
 if($tex.val()=="") 
 { 
  $("p").html("您还可以输入的字数<span>140</span>"); 
 } 
 }) 
 $tex.blur(function(){ 
 if($tex.val() == "") 
 { 
  $("p").html("请在下面输入您的文字:"); 
 } 
 }) 
 if(ie) 
 { 
  $tex[0].oninput = changeNum; 
 } 
 else 
 { 
  $tex[0].onpropertychange = changeNum; 
 } 
 
 function changeNum() 
 { 
 //汉字的个数 
 str=($tex.val().replace(/\w/g,"")).length; 
 //非汉字的个数 
 abcnum=$tex.val().length-str; 
 total=str*2+abcnum; 
 if(str*2+abcnum<maxNum||str*2+abcnum==maxNum) 
 { 
  $but.removeClass() 
  $but.addClass("but"); 
  texts=Math.ceil((maxNum-(str*2+abcnum))/2); 
  $("p").html("您还可以输入的字数<span>"+texts+"</span>").children().css({"color":"blue"}); 
 } 
 else if(str*2+abcnum>maxNum) 
 { 
  $but.removeClass("") 
  $but.addClass("grey"); 
  texts =Math.ceil(((str*2+abcnum)-maxNum)/2); 
  $("p").html("您输入的字数超过了<span>"+texts+"</span>").children("span").css({"color":"red"}); 
 } 
 } 
}) 
</script> 
</head> 
<body> 
<div class="box"> 
 <p>请在下面输入您的文字:</p> 
 <textarea name="weibao" class="tex" cols="" rows="8"></textarea> 
</div> 
</body> 
</html>

I hope this article will be helpful to everyone in learning javascript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn