用jquery判斷輸入框還可以輸入多少字,jquery判斷輸入框
效果
全部代碼,粘貼可用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style>
#comment textarea{height:100px;}
#comment p span{color:red;}
</style>
<script src="js/jquery-1.7.1.min.js" ></script>
</head>
<body>
<div id="comment">
<textarea></textarea>
<p>你還可以輸入<span>300</span>個字</p>
</div>
<script>
$(function(){
$(' #comment textarea ').keyup(function(){ //輸入字元後鍵盤up時觸發事件
var txtLeng = $(' #comment textarea ').val().length; //把輸入字元的長度賦給txtLeng
//拿輸入的值做判斷
if( txtLeng>300 ){
//輸入長度大於300時span顯示0
$(' #comment p span ').text(' 0 ');
//截取輸入內容的前300個字元,賦給fontsize
var fontsize = $('#comment textarea').val().substring(0,300);
//顯示到textarea上
$(' #comment textarea ').val( fontsize );
}else{
//輸入長度小於300時span顯示300減去長度
$('#comment p span').text(300-txtLeng);
}
});
});
</script>
</body>
</html>
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。