Jun
30
2009

จำกัดจำนวนตัวอักษรใน textarea

1,456 views

บางครั้งเราต้องการจำกัดจำนวนตัวอักษรใน textarea ปรากฏว่ามันไม่ง่ายเหมือน text box ที่เราสามารถใส่ attribute maxlength เข้าไปจำกัดตัวอักษรได้ตรงๆ จึงต้องใช้ jquery เข้ามาช่วยดังตัวอย่าง

 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
	$('#Wish').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}
		$('#WishMax').html('เหลืออีก ' + (max - $(this).val().length) + ' ตัวอักษร');
	});
});
</script>
 
<textarea name="Wish" id="Wish" maxlength="10"></textarea>
<div id="WishMax"></div>
 

Written by Pipo in: Web Developer | Tags: , , ,

1 Comment »

  • ขอบคุณมากเลยครับ

    Comment by killer777 — July 17, 2009

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes