Input placeholder bằng jQuery

Trở về

  • 3,928

Placeholder hiện nay được sử dụng khá dễ dàng với html5, tuy nhiên đối với html hay xhtml thì việc dùng js hay jquery lại khá quan trọng.

input 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 input = $('input[type="text"]');
    input.focus(function() {
        $(this).addClass('focusField');
        if (this.value == this.defaultValue){ 
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });
    input.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;
}
input {
    color: #999;
    width: 300px;
}
.focusField { color: #000; }
.fillField { color: #000; }
</style>
</head>
<body>
<input type="text" value="Focus và gõ text để thấy kết quả" />
</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.