[blog]

Hướng dẫn các bạn cách làm hiển thị biểu tượng icon xóa cho thẻ Input đơn giản nhất, thích hợp để áp dụng cho khung search, khung tìm kiếm cho blogspot

Hướng dẫn hiển thị nút Xóa, Delete, Clear cho thẻ HTML Input

Như trên là một thẻ HTML Input khi nhập văn bản vô thì xuất hiện bên cạnh là nút Xóa

Cách thứ nhất: Cách đơn giản là chúng ta tạo thẻ Input như sau:

<input type = "search"/> thì tự động xuất hiện biểu tượng icon xóa.

<input type = "text"/> không có biểu tượng icon xóa.

Cách thứ hai: Cách dùng <input type = "text"/> muốn hiện icon xóa thì chúng ta cần phải viết thêm Javascript và Css như sau:

1. JavaScript:

<script>

    //<![CDATA[

    function tog(v) {

        return v ? 'addClass' : 'removeClass';

    }

    $(document).on('input', '.clearable', function() {

        $(this)[tog(this.value)]('x');

    }).on('mousemove', '.x', function(e) {

        $(this)[tog(this.offsetWidth - 18 < e.clientX - this.getBoundingClientRect().left)]('onX');

    }).on('touchstart click', '.onX', function(ev) {

        ev.preventDefault();

        $(this).removeClass('x onX').val('').change();

    });

    //]]>

</script>

2. CSS


<style>

.clearable{background:#fff url(data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=) no-repeat right -10px center;border:1px solid #999;padding:3px 18px 3px 4px;border-radius:3px;transition:background 0.4s}

.clearable.x{background-position:right 5px center}

.clearable.onX{cursor:pointer}

.clearable::-ms-clear{display:none;width:0;height:0}

</style>

3. HTML

<input class="clearable" type="text" name="" value="" placeholder="" />

Với cách làm thứ hai chúng ta cần sử dụng thư viện jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
[/blog]