Textarea placeholder bằng jQuery

Trở về

  • 2,991

Cũng tương tự như input, chúng ta cũng có thể sử dụng cho textarea.

textarea tự động ẩn hiện giá trị khi focus

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Học Web Chuẩn</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    var textarea = $('textarea');
    textarea.focus(function() {
        $(this).addClass('focusField');
        if (this.value == this.defaultValue){ 
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });
    textarea.blur(function() {
        $(this).removeClass('focusField');
            $(this).removeClass('focusField').addClass('fillField');
        if ($.trim(this.value) == ''){
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass('fillField');
        }
    });
});
</script>
<style>
* { /* reset lại margin và padding cho các tag */
    margin: 0;
    padding: 0;
}
textarea {
    color: #999;
    width: 400px;
}
.focusField { color: #000; }
.fillField { color: #000; }
</style>
</head>
<body>
<textarea cols="20" rows="5">Focus và gõ text để thấy kết quả</textarea>
</body>
</html>

Hiển thị trình duyệt:

Download file để thực hành

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.