先前介紹過一個類似效果的 jQuery maxlength 外掛,而這次的 charCount 部署更簡單,還多了「超出字數提示」的功能,整體使用體驗很接近 Twitter 的輸入框。
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/charCount.js"></script>
<form id="form" method="post" action="">
<h2>Default Usage</h2>
<div>
<label for="message">Type your message</label>
<textarea id="message1" name="message1"></textarea>
</div>
<h2>Custom Usage</h2>
<div>
<label for="message">Another message (limited to 30, warning at 10)</label>
<textarea id="message2" name="message2"></textarea>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
//預設用法
$("#message1").charCount();
//自訂用法
$("#message2").charCount({
allowed: 30,
warning: 10,
counterText: '剩余字數: '
});
});
</script>
透過 allowed 設定可輸入的上限、warning 設定開始警示的門檻,counterText 則能自訂提示文字,讓輸入框在使用者接近上限時給出友善提醒。