thực hành - Xóa text trường input

Trong bài thực hành này, chúng ta sẽ sử dụng JavaScript để xóa văn bản trong trường input khi người dùng click vào nó.

Xóa text trường input


Click vào trường input để xem hiệu ứng

 

Xem kết quả

Cách xóa text trường input


Bước 1) Thêm HTML:

Ví dụ

<div class="containerx">
    <form action="/action_page.php" method="post">
        <input type="text" id="text" name="text" value="Your text here..." required="required" />
        <button type="submit">Submit</button>
    </form>
</div>

Bước 2) Thêm CSS:

Ví dụ

/* Tạo kiểu cho vùng chứa */
.containerx {
    padding:15px 20px;
    background-color:#ddd;
    border-radius:5px;    
}
/* Tạo kiểu cho phần tử input */
form > input {
    padding:10px;
    border:none;
    border-radius:5px;
    display:block;
    margin-bottom:15px;    
}
/* Tạo kiểu cho phần tử button */
form > button {
    border:none;
    outline:none;
    padding:10px 20px;
    background-color:royalblue;
    color:white;
    cursor:pointer;    
    border-radius:5px;
}
/* Thêm hiệu ứng khi hover */
form > button:hover {
    background-color:orange;    
}

Bước 3) Thêm JavaScript:

Ví dụ

<script>
    // Khai báo biến
    var text;
    text = document.getElementById('text');
    
    // Gán sự kiện focus
    text.onfocus = function() {
        this.value = "";    
    }
</script>

Xem kết quả