Examples are copy / pasted from here.
First example with JS.
HTML:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/index.css"/> <script type="text/javascript" src="/jquery-2.1.1.js"></script> <script type="text/javascript" src="/index.js"></script> </head> <body> Enter something: <input class="clearable" type="text" name="" value="" placeholder="" /> <body> </html>
CSS:
.clearable{ background: #fff url(icoX.gif) no-repeat right -10px center; border: 1px solid #999; padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */ border-radius: 3px; transition: background 0.4s; } .clearable.x { background-position: right 5px center; } /* (jQ) Show icon */ .clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
JS:
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('click', '.onX', function(){ $(this).removeClass('x onX').val('').change(); });
Example you can download from here.
---
Another example, pure CSS, no JS needed.
HTML:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/index.css"></link> </head> <h1> Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span> </h1> <div class="search-wrapper"> <form> <input type="text" name="focus" required class="search-box" placeholder="Enter search term" /> <button class="close-icon" type="reset"></button> </form> </div> </html>
Here notice line:
<button class="close-icon" type="reset"></button>
CSS:
.search-box,.close-icon,.search-wrapper { position: relative; padding: 10px; } .close-icon { border:1px solid transparent; background-color: transparent; display: inline-block; vertical-align: middle; outline: 0; cursor: pointer; } .close-icon:after { content: "X"; display: block; width: 15px; height: 15px; position: absolute; background-color: #FA9595; z-index:1; right: 35px; top: 0; bottom: 0; margin: auto; padding: 2px; border-radius: 50%; text-align: center; color: white; font-weight: normal; font-size: 12px; box-shadow: 0 0 2px #E50F0F; cursor: pointer; } .search-box:not(:valid) ~ .close-icon { display: none; }
Example you can download from here.
---
HTML5 approach
HTML:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/index.css"> </head> <body> Normal search: <input type="search"> <p/> Search with mask: <input type="search" isPassword="true"> </body> </html>
CSS:
input[isPassword="true"] { -webkit-text-security: disc; }
Notice that input type is "search".
Example you can download from here.