185

I want to have a nice little icon that, when clicked will clear the text in the <INPUT> box.

This is to save space rather than having a clear link outside of the input box.

My CSS skills are weak... Here is a screenshot photo of how the iPhone looks.

Hugh Buchanan
  • 2,011
  • 3
  • 14
  • 9

11 Answers11

256

Nowadays with the <input type="search"> element, it's pretty simple:

<input type="search" placeholder="Search..."/>

Supported browsers will automatically render a usable clear button in the field by default.

plain HTML5 search input field

The clear button is a ::-webkit-search-cancel-button CSS pseudo-element automatically inserted by Webkit/Blink-based browsers (though it's technically still a non-standard feature).


If you use Bootstrap, you'll have to add a CSS override to force the pseudo-element to show:

input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

bootstrap search input field


Officially, the -webkit-search-cancel-button psuedo-element is non-standard and should not be relied upon as a built-in HTML feature across browsers.

Notably Firefox does not render the clear button by default as of version 110, but they have plans to enable it eventually: https://bugzilla.mozilla.org/show_bug.cgi?id=1654288. You can check up-to-date browser compatibility information on MDN or CanIUse.com.

The most reliable, future-proof, cross-browser approach is to use a form with an explicit <input type="reset"/> element nearby to allow clearing the Search form with a button. This also makes it easier to add accecibility hints and style the clear button directly with CSS.

<form action="/search">
  <input type="search" placeholder="Search..."/>
  <input type="reset" value="X" alt="Clear the search form">
  <input type="submit" value="Search">
</form>

Search with manual input reset button appended


Extras: Safari/WebKit browsers can also provide extra features when using type="search", like results=5, enterkeyhint="...", and autosave="...", but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:

input[type=search] {
    -webkit-appearance: none;
}

See the MDN Documentation, CanIUse.com, or CSS-Tricks.com for more complete and up-to-date info about the features provided by <input type="search"/> in browsers today.

Nick Sweeting
  • 5,364
  • 5
  • 27
  • 37
  • 4
    Excellent answer, no code involved. Unfortunately not supported by many browsers.. Nevermind, would be a Chrome additional feature in my product :) – guillaumepotier Jul 21 '17 at 12:51
  • 1
    It's better now https://caniuse.com/input-search –  Sep 29 '21 at 18:02
  • How about tailwind? Mine doesn't appear and tailwind docs come up empty – Justin Nov 25 '21 at 00:28
  • 3
    @Justin I believe tailwind disables the webkit styling on multiple levels, so you may have to force: `input[type=search] {-webkit-appearance: searchfield !important;}` `input[type=search]::-webkit-search-cancel-button {-webkit-appearance: searchfield-cancel-button !important;}` – Nick Sweeting Mar 22 '22 at 21:26
  • You can also try this: `input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-results-button, input[type="search"]::-webkit-search-results-decoration { -webkit-appearance: initial !important; }` – Nick Sweeting Mar 22 '22 at 23:07
  • 1
    Not supported by Firefox 99 (2022). – Luis A. Florit Apr 10 '22 at 21:50
  • @LuisA.Florit Firefox has support behind a flag and they plan to enable it by default soon: https://bugzilla.mozilla.org/show_bug.cgi?id=1654288 (updated my answer as well with an alternative approach for Firefox using ``). – Nick Sweeting Jan 31 '23 at 02:53
106

Since HTML5, you could use <input type="search">. But this isn't necessarily customizable. In case you'd like to have full control over the UI, here are two kickoff examples. One with jQuery and another without.

With jQuery:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532</title>
        <script src="https://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('input.deletable').wrap('<span class="deleteicon"></span>').after($('<span>x</span>').click(function() {
                    $(this).prev('input').val('').trigger('change').focus();
                }));
            });
        </script>
        <style>
            span.deleteicon {
                position: relative;
                display: inline-flex;
                align-items: center;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                right: 3px;
                width: 15px;
                height: 15px;
                border-radius: 50%;
                color: #fff;
                background-color: #ccc;
                font: 13px monospace;
                text-align: center;
                line-height: 1em;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 18px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <input type="text" class="deletable">
    </body>
</html>

Without jQuery

jQuery is not strictly necessary, it just nicely separates the logic needed for progressive enhancement from the source, you can of course also go ahead with plain HTML/CSS/JS:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532, with "plain" HTML/CSS/JS</title>
        <style>
            span.deleteicon {
                position: relative;
                display: inline-flex;
                align-items: center;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                right: 3px;
                width: 15px;
                height: 15px;
                border-radius: 50%;
                color: #fff;
                background-color: #ccc;
                font: 13px monospace;
                text-align: center;
                line-height: 1em;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 18px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <span class="deleteicon">
            <input type="text">
            <span onclick="var input = this.previousElementSibling; input.value = ''; input.focus();">x</span>
        </span>
    </body>
</html>

You only end up with uglier HTML (and non-crossbrowser compatible JS ;) ).

Again, if the UI look'n'feel isn't your biggest concern, but the functionality is, then just use <input type="search"> instead of <input type="text">. It'll show the (browser-specific) clear button on HTML5 capable browsers.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
68

HTML5 introduces the 'search' input type that I believe does what you want.

<input type="search" />

Here's a live example.

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
  • 7
    Although the 'search' type is supported by all recent browsers (check support here: wufoo.com/html5 ), the clear button is not shown in Firefox (32.0.3) or Opera (12.17). – justanotherprogrammer Sep 30 '14 at 14:57
  • 15
    the clear button is not shown in latest Chrome either – tsayen Apr 29 '15 at 09:03
  • 4
    If you're using Bootstrap, it [may override the default behaviour](https://github.com/twbs/bootstrap/issues/5624) – ᴍᴇʜᴏᴠ Dec 29 '16 at 11:52
  • The linked CodePen is missing the closing slash in the input, so if you want to see it work on CodePen, just add the closing slash. – Gen1-1 Jun 05 '20 at 19:51
  • @Gen1-1 oops, looks like public uploads are disabled https://blog.codepen.io/2019/08/06/anonymous-pen-save-option-removed/ if anyone has a fixed code pen, please feel free to edit and help correct the demo – ThorSummoner Jun 06 '20 at 18:32
26

Check out our jQuery-ClearSearch plugin. It's a configurable jQuery plugin - adapting it to your needs by styling the input field is straightforward. Just use it as follows:

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

Example

Matthew Hegarty
  • 3,791
  • 2
  • 27
  • 42
wldaunfr
  • 589
  • 7
  • 8
  • This is awesome, but I would advice adding in "$(window).resize(function() {triggerBtn()});" in jquery.clearsearch.js, just after $this.on('keyup keydown change focus', triggerBtn); | So that resize windows will not messed up the cross position – Ng Sek Long Feb 15 '18 at 04:29
18

You can't actually put it inside the text box unfortunately, only make it look like its inside it, which unfortunately means some css is needed :P

Theory is wrap the input in a div, take all the borders and backgrounds off the input, then style the div up to look like the box. Then, drop in your button after the input box in the code and the jobs a good'un.

Once you've got it to work anyway ;)

Tom
  • 4,257
  • 6
  • 33
  • 49
17

Of course the best approach is to use the ever-more-supported <input type="search" />.

Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:

form{
    position: relative;
    width: 200px;
}

form input {
    width: 100%;
    padding-right: 20px;
    box-sizing: border-box;
}

form input:placeholder-shown + button{
  opacity: 0;
  pointer-events: none;
} 

form button {
    position: absolute;
    border: none;
    display: block;
    width: 15px;
    height: 15px;
    line-height: 16px;
    font-size: 12px;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: 5px;
    margin: auto;
    background: #ddd;
    padding: 0;
    outline: none;
    cursor: pointer;
    transition: .1s;
}
<form>
        <input type="text" placeholder=" " />
        <button type="reset">&times;</button>
</form>
vsync
  • 118,978
  • 58
  • 307
  • 400
Niki Romagnoli
  • 1,406
  • 1
  • 21
  • 26
8

I got a creative solution I think you are looking for

$('#clear').click(function() {
  $('#input-outer input').val('');
});
body {
  font-family: "Tahoma";
}
#input-outer {
  height: 2em;
  width: 15em;
  border: 1px #e7e7e7 solid;
  border-radius: 20px;
}
#input-outer input {
  height: 2em;
  width: 80%;
  border: 0px;
  outline: none;
  margin: 0 0 0 10px;
  border-radius: 20px;
  color: #666;
}
#clear {
  position: relative;
  float: right;
  height: 20px;
  width: 20px;
  top: 5px;
  right: 5px;
  border-radius: 20px;
  background: #f1f1f1;
  color: white;
  font-weight: bold;
  text-align: center;
  cursor: pointer;
}
#clear:hover {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-outer">
  <input type="text">
  <div id="clear">
    X
  </div>
</div>

https://jsfiddle.net/qdesign/xn9eogmx/1/

3

Firefox doesn't seem to support the clear search field functionality... I found this pure CSS solution that works nicely: Textbox with a clear button completely in CSS | Codepen | 2013. The magic happens at

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

body {
    background-color: #f1f1f1;
    font-family: Helvetica,Arial,Verdana;

}
h2 {
    color: green;
    text-align: center;
}
.redfamily {
    color: red; 
}
.search-box,.close-icon,.search-wrapper {
    position: relative;
    padding: 10px;
}
.search-wrapper {
    width: 500px;
    margin: auto;
}
.search-box {
    width: 80%;
    border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.search-box:focus {
    box-shadow: 0 0 15px 5px #b0e0ee;
    border: 2px solid #bebede;
}
.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;
}
<h2>
    Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<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>

I needed more functionality and added this jQuery in my code:

$('.close-icon').click(function(){ /* my code */ });
brasofilo
  • 25,496
  • 15
  • 91
  • 179
1

Maybe this simple solution can help:

<input type="text" id="myInput" value="No War"/><button onclick="document.getElementById('myInput').value = ''" title="Clear">X</button></input>
  • While this code may provide a solution to OP's problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – E. Zeytinci Jan 07 '20 at 18:33
  • OP specifically stated he wanted the button INSIDE the input to save space. – user9645 Jan 21 '21 at 14:05
  • Neat and simple solution, I've quickly implemented it in my little page: https://carloswm85.github.io/subsites/csharp-notes/ Thanks. – carloswm85 Jul 31 '22 at 02:06
0

@Mahmoud Ali Kaseem

I have just changed some CSS to make it look different and added focus();

https://jsfiddle.net/xn9eogmx/81/

$('#clear').click(function() {
  $('#input-outer input').val('');
  $('#input-outer input').focus();
});
body {
  font-family: "Arial";
  font-size: 14px;
}
#input-outer {
  height: 2em;
  width: 15em;
  border: 1px #777 solid;
  position: relative;
  padding: 0px;
  border-radius: 4px;
}
#input-outer input {
  height: 100%;
  width: 100%;
  border: 0px;
  outline: none;
  margin: 0 0 0 0px;
  color: #666;
  box-sizing: border-box;
  padding: 5px;
  padding-right: 35px;
  border-radius: 4px;
}
#clear {
  position: absolute;
  float: right;
  height: 2em;
  width: 2em;
  top: 0px;
  right: 0px;
  background: #aaa;
  color: white;
  text-align: center;
  cursor: pointer;
  border-radius: 0px 4px 4px 0px;
}
#clear:after {
  content: "\274c";
  position: absolute;
  top: 4px;
  right: 7px;
}
#clear:hover,
#clear:focus {
  background: #888;
}
#clear:active {
  background: #666;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-outer">
  <input type="text">
  <div id="clear"></div>
</div>
Hiren
  • 56
  • 6
-5

It is so simple in HTML5

<input type="search">

This will do your job!

Mohammed mansoor
  • 743
  • 3
  • 11
  • 18
  • 4
    it's also simple to see others have *already* said that, **years before** you, in this thread. – vsync Jan 25 '21 at 15:07