226

Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?

I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?

I want the icon inside the input text element, something like:

--------------------------------------------------
|                                               X|
--------------------------------------------------
brasofilo
  • 25,496
  • 15
  • 91
  • 179
Giovanni Di Milia
  • 13,480
  • 13
  • 55
  • 67
  • 3
    A jQuery plugin to position an image over an input box? Am I missing something or what?! – Christian Jun 06 '11 at 22:19
  • 1
    @Christian Sciberras As you can see from the answer I chose, it can be a jquery plugin... – Giovanni Di Milia Jun 08 '11 at 17:04
  • 1
    You can have a jQuery plugin to show plain alert boxes. It doesn't mean you really *have to*, and in most cases, *it is over-engineered bloat*. Oh and by the way, what you selected **isn't a jQuery plugin**, but a mix of javascript, html and css. A plugin would be a single file/script with the jQuery signature containing the relevant details. – Christian Jun 08 '11 at 19:26
  • 1
    @Christian Sciberras: I can distinguish between a jQuery plugin and a mix of javascript and CSS. What I was saying is that if you want to do something nice, you cannot put only an image on an input box. – Giovanni Di Milia Jun 08 '11 at 21:40
  • Folks looking for this issue will need this information as well: [**How do you detect the clearing of a “search” HTML5 input?**](https://stackoverflow.com/a/25569880/1287812) – brasofilo Jul 01 '18 at 21:51
  • a plugin doesn't need to be a single file and it can indeed be a mix of html, css and jquery so good for you @GiovanniDiMilia for standing your ground! – luke_mclachlan Jul 25 '18 at 15:47

18 Answers18

435

Add a type="search" to your input
The support is pretty decent but will not work in IE<10

<input type="search">

Older browsers

If you need IE9 support here are some workarounds

Using a standard <input type="text"> and some HTML elements:

/**
 * Clearable text inputs
 */
$(".clearable").each(function() {
  
  const $inp = $(this).find("input:text"),
      $cle = $(this).find(".clearable__clear");

  $inp.on("input", function(){
    $cle.toggle(!!this.value);
  });
  
  $cle.on("touchstart click", function(e) {
    e.preventDefault();
    $inp.val("").trigger("input");
  });
  
});
/* Clearable text inputs */
.clearable{
  position: relative;
  display: inline-block;
}
.clearable input[type=text]{
  padding-right: 24px;
  width: 100%;
  box-sizing: border-box;
}
.clearable__clear{
  display: none;
  position: absolute;
  right:0; top:0;
  padding: 0 8px;
  font-style: normal;
  font-size: 1.2em;
  user-select: none;
  cursor: pointer;
}
.clearable input::-ms-clear {  /* Remove IE default X */
  display: none;
}
<span class="clearable">
  <input type="text" name="" value="" placeholder="">
  <i class="clearable__clear">&times;</i>
</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Using only a <input class="clearable" type="text"> (No additional elements)

Clear icon inside input element

set a class="clearable" and play with it's background image:

/**
 * Clearable text inputs
 */
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();
});

// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
/*
    Clearable text inputs
*/
.clearable{
  background: #fff url(https://i.stack.imgur.com/mJotv.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 */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
<input class="clearable" type="text" name="" value="" placeholder="" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

The trick is to set some right padding (I used 18px) to the input and push the background-image right, out of sight (I used right -10px center).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class "x" (if input has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x and detect on mousemove if the mouse is inside that 18px "x" area; if inside, add the class onX.
Clicking the onX class removes all classes, resets the input value and hides the icon.


7x7px gif: Clear icon 7x7

Base64 string:

data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 5
    I took the liberty of borrowing some of the ideas in this code to make a tag cloud generator (with pure css tags and upvote and downvote buttons). I hope it looks ok in your browser; check it out at http://jsfiddle.net/7PnKS/ – mrBorna Sep 01 '11 at 18:29
  • which to be displayed when the input not empty either after submit without focus on – khaled_webdev Nov 22 '12 at 10:09
  • @roXon that's a nice example, but unfortunately it's going to cause a blur event as soon as one clicks the "X". And often times, blur events are handling input validations. I guess I'd have to stop that in the click function? – tim Mar 25 '13 at 17:55
  • @tim http://jsfiddle.net/PJZmv/1326/ Just reassign `.focus()` to the *input* element. – Roko C. Buljan Mar 25 '13 at 18:06
  • 1
    Wow, really nice solution. That's what I am looking for. Thank you. But, how can I change the "x" image to using the Bootstrap 3 glyphicon? Because the glyphicon is font, therefore, it display better when it zoom out. – user1995781 Oct 17 '13 at 01:47
  • @riley Thanks for pointing out that issue. Seems related to some Webkit bug. **The fix is to remove any CSS3 animation transition** like: http://jsfiddle.net/6LZhq/ until they fix it. – Roko C. Buljan Feb 20 '14 at 07:05
  • 1
    Nice, but the background image can clash with other CSS. The answer below by wldaunfr refers to a neat jQuery plug-in: http://plugins.jquery.com/clearsearch/ – Nick Westgate Feb 21 '14 at 00:12
  • We use Kendo inputs that already use a background image. I posted the comment above for a reason! – Nick Westgate Feb 21 '14 at 02:45
  • @NickWestgate never used Kendo, but should you be able to wrap your transparent input inside a parent that will have the background? – Roko C. Buljan Feb 21 '14 at 11:37
  • The Kendo framework puts the background image in the input. Sure, I could override that or something, but it was easier to use something that just works; namely the clearsearch jQuery plug-in. – Nick Westgate Mar 03 '14 at 00:03
  • very compact solution! just hoped i could do it without listening to mousemove... – Guntram Sep 16 '14 at 10:13
  • @Guntram you don't have to. But than you'll lose the mouse pointer cursor. If you're ok with that than remove the `.onX`: http://jsbin.com/bebug/6/edit – Roko C. Buljan Sep 16 '14 at 10:59
  • 1
    works nicely for me in latest firefox and chrome. but had to change `.on('touchstart click', '.onX', ...` to `.on('touchstart click', '.onX, .x', ...` to make it work on iOS. – kritzikratzi Jul 11 '15 at 10:46
  • It doesn't work in Chrome when value of the field is pasted automatically from browser's cache – Andremoniy Oct 15 '15 at 09:14
  • @RokoC.Buljan It doesn't help :( – Andremoniy Oct 15 '15 at 09:18
  • @Andremoniy Simply add `$('.clearable').trigger("input");` after the script like: http://jsbin.com/bebug/10/edit?html,css,js,output to trigger the `"input"` event. – Roko C. Buljan Oct 15 '15 at 09:21
  • @RokoC.Buljan Unfortunatelly, no :( Have you tried it? I'm talking about cached values for input textfields, which are highlighted by yellow color when become autofilled. – Andremoniy Oct 15 '15 at 09:27
  • Furthemore, in IE11 appear two "x" buttons - one from IE itselft, one from your script. It is very ugly :( – Andremoniy Oct 15 '15 at 09:29
  • @RokoC.Buljan Sure, I'm not using `type="search"`. IE 11 adds "x" independently for `type="text"`. – Andremoniy Oct 15 '15 at 09:36
  • @Andremoniy thanks for notifying about IE11/Edge, **fixed!** See the added line in CSS – Roko C. Buljan Oct 15 '15 at 09:47
  • i'm using this in a rails app and running into strange bug, i had to add `$(document).on('blur', '.clearable', function(e){ $('.clearable').trigger("input"); });` – coderVishal Dec 07 '15 at 08:57
  • @coderVishal strange bug. yes. Why would you ever need blur on document? – Roko C. Buljan Dec 07 '15 at 08:58
  • @RokoC.Buljan. When i hit the cross button the inputbox value clears up as expected. But when i remove the focus from the element without typing anything(after hitting the cross),the inputbox value returns to it original value?. This strange autocompletion does not happen if I clear text using backspace – coderVishal Dec 07 '15 at 09:09
  • @coderVishal what *initial* value? I don't get it... if you don't type anything what value do you want to see? – Roko C. Buljan Dec 07 '15 at 09:10
  • @RokoC.Buljan Sorry for lack of context. I have values being pre-loaded from server. Say i have input box that has value "hello world"when page loaded. Now i hit the cross mark it clears up. Now if i without typing remove the focus from the inputbox, it returns back to "hello world" – coderVishal Dec 07 '15 at 09:13
  • @RokoC.Buljan I'm using blur only on clearable class of the document. I dont understand why it works though. Will get back to you if i find a answer – coderVishal Dec 07 '15 at 09:26
  • @RokoC.Buljan Your code is working fine on my desktop browsers. However, it does not work on my iPhone browsers (Chrome & Safari). Please advise. – Withhelds Jun 22 '16 at 16:35
  • @Withhelds humm I don't own an iPhone... perhaps you can explain what's going on? – Roko C. Buljan Jun 22 '16 at 16:37
  • 1
    @RokoC.Buljan I just tested again and here is my findings 1) Input few characters in the input text box 2) 'X' icon appears 3) Tried Click on the 'X' icon but the text text does not clear away. Note: At this point of time, the iPhone keyboard is still active and not hidden. 4) If I clicked on "Done" button to hide the keyboard and then click back on the 'X' icon, the text will be cleared correctly now. Seems like I am unable to clear the text with 'X' when the iPhone keyboard is shown. – Withhelds Jun 22 '16 at 16:58
  • @Withhelds hey I'm also having the same issue...Have you been able to figure out a fix? I'm looking into it now but I was starting to believe it had something to do with: this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left because that bit of code deals with mouse position etc and that doesn't exist on an iOS device. – Mickey Sly Jul 29 '16 at 13:07
  • @RokoC.Buljan Hey Roko! First I just wanted to say I really appreciate the reply and the effort to fix this. Unfortunately that fix didn't help. It doesn't seem to close unless the keyboard is down... and even if the keyboard is down its also kind of a pain to hit the X. Im guessing its because of my fat fingers and its looking for a small click area. Is there a way to maybe increase the area that it detects the press? That might solve it – Mickey Sly Jul 29 '16 at 13:30
  • 1
    @MickeySly hummm please see this edit: http://jsbin.com/dofaxa/4 and let me know! (thanks) – Roko C. Buljan Jul 29 '16 at 14:23
  • @RokoC.Buljan Hey, it still didn't work but it's alright. I'm actually working with angular so I'm actually utilizing some of your answer and making an angular-ized solution that seems to work even when the keyboard is up. I'll post an answer to this thread once I've fully implemented it. – Mickey Sly Jul 29 '16 at 14:46
  • @MickeySly I am currently using this solution http://blog.sodhanalibrary.com/2015/12/search-box-with-reset-button-using.html#.V5yAMJN96t8 – Withhelds Jul 30 '16 at 10:26
  • @RokoC.Buljan: jsbin.com/dofaxa/4 this script is nt working on ios devices – CodeMan Aug 03 '16 at 09:06
  • That one works better on iOS and respects the onchange event. Change: `$(document).on('input'` to `$(document).on('input change'` and add `}).on('touchstart', '.x', function( e ){ $(this)[tog(this.offsetWidth-25 < e.originalEvent.touches[0].pageX-this.getBoundingClientRect().left)]('onX'); if( $(this).hasClass('onX') ) { $(this).removeClass('x onX').val('').change(); }` after `$(this)[tog(this.value)]('x');` – xsigndll Oct 08 '16 at 20:56
  • 1
    My problem with the first option: **The OP did not specify that this is a search box**, only that it should have a clear button like the Google search box. And as good semantic web developers, we should not label it as such if that's not what it is. This will mislead search engines, screen readers, and anything else that reads the markup rather than the rendered UI into thinking it is a search box. – sfarbota Sep 05 '17 at 22:02
  • Also, what does `LS` mean here?: `// Uncomment the line above if you pre-fill values from LS or server` – sfarbota Sep 05 '17 at 22:03
  • @RokoC.Buljan during pandemic, this answer helped me have less problems ;) – Suhail Mumtaz Awan Aug 17 '20 at 04:37
  • The ```type=search``` approach doesn't work for me (the snippet in the answer didn't show an X). I tested it in FireFox 81.0.2 on Windows 10. – bob Oct 23 '20 at 22:58
  • `type=search` doesn't wok with Firefox 83 or Waterfox 2020.10 while it does with Chrome 86.0.4240.111 and Opera 72.0.3815.148 (all on Windows 10). – Andreas Nov 18 '20 at 13:18
  • I like the `class="clearable"` solution a lot because I think it looks even better than the standard 'x'. :) – Andreas Nov 18 '20 at 13:23
  • @RokoC.Buljan I think some words that explain the jQuery toggle part of the last example in your answer might be very helpful! ;) – Andreas Nov 19 '20 at 07:56
  • 1
    @Andreas the `tog` function is just a way to infer a somewhat different behavior of jQuery `toggleClass()` method. If I used the `.toggleClass("x", bool)` I would have to use double negation `("x", !!bool)` (just like I did in the other example: `$cle.toggle(!!this.value)`). Try to use for example instead of `$(this)[tog(this.value)]("x");` this one: `$(this).toggleClass("x", this.value);` and see: the class gets toggled on every keystroke! If you instead use `!!this.value` the problem is gone. You can either rewrite the whole using `.toggleClass` and double negations or keep it as is :) – Roko C. Buljan Nov 19 '20 at 12:55
63

Could I suggest, if you're okay with this being limited to html 5 compliant browsers, simply using:

<input type="search" />

JS Fiddle demo

Admittedly, in Chromium (Ubuntu 11.04), this does require there to be text inside the input element before the clear-text image/functionality will appear.

Reference:

brasofilo
  • 25,496
  • 15
  • 91
  • 179
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 13
    an help to other developers: If you use bootstrap CSS platform remove style "-webkit-appearance: textfield;" in the bootstrap.css input[type="search"] { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; -webkit-appearance: textfield; } – Riccardo Bassilichi May 21 '14 at 13:40
  • 1
    Is there a way to change the color of the X? – Howard Mar 11 '15 at 13:46
  • 2
    @RiccardoBassilichi is there a way to extend my css file so that i don't have to edit the original bootstrap.css and still get this working? – supersan Jun 15 '15 at 19:25
  • I think no! But I'm not a css wizard! :-( – Riccardo Bassilichi Jun 16 '15 at 20:23
  • Answer here: http://stackoverflow.com/questions/13956868/html5-search-input-does-not-work-with-bootstrap#18813579 – ejntaylor Mar 15 '17 at 12:11
  • 6
    Unfortunately this is not supported by Firefox, see : https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button – Guillaume Husta Jan 03 '20 at 21:42
  • `type=search` doesn't wok with Firefox 83 or Waterfox 2020.10 while it does with Chrome 86.0.4240.111 and Opera 72.0.3815.148 (all on Windows 10). – Andreas Nov 18 '20 at 13:18
33

According to MDN, <input type="search" /> is currently supported in all modern browsers:

input type=search

<input type="search" value="Clear this." />

However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:

Option 1 - Always display the 'x': (example here)

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Always display the 'x':</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>

Option 2 - Only display the 'x' when hovering over the field: (example here)

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
  display: block;
}
.clearable-input > [data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Only display the 'x' when hovering over the field:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>

Option 3 - Only display the 'x' if the input element has a value: (example here)

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
  var input = el.querySelector('input');

  conditionallyHideClearIcon();
  input.addEventListener('input', conditionallyHideClearIcon);
  el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
    input.value = '';
    conditionallyHideClearIcon();
  });

  function conditionallyHideClearIcon(e) {
    var target = (e && e.target) || input;
    target.nextElementSibling.style.display = target.value ? 'block' : 'none';
  }
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Only display the 'x' if the `input` element has a value:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
30

You could use a reset button styled with an image...

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

See it in action here: http://jsbin.com/uloli3/63

KOGI
  • 3,959
  • 2
  • 24
  • 36
26

I've created a clearable textbox in just CSS. It requires no javascript code to make it work

below is the demo link

http://codepen.io/shidhincr/pen/ICLBD

Shidhin Cr
  • 868
  • 8
  • 19
9

Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch -

using it is as easy as:

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

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

​ Example: http://jsfiddle.net/wldaunfr/FERw3/

wldaunfr
  • 589
  • 7
  • 8
5

If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

Example: http://jsfiddle.net/VTvNX/

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
4

Change the text box type as 'search' in the design mode or

<input type="search">
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Aruna Prabhath
  • 206
  • 2
  • 10
3

EDIT: I found this link. Hope it helps. http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html

You have mentioned you want it on the right of the input text. So, the best way would be to create an image next to the input box. If you are looking something inside the box, you can use background image but you may not be able to write a script to clear the box.

So, insert and image and write a JavaScript code to clear the textbox.

Jaspero
  • 2,912
  • 6
  • 26
  • 30
3

Use simple absolute positioning - it's not that hard.

jQuery:

$('span').click(function(){
  $('input', $(this).parent()).val('');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>

Vanilla JS:

var spans = document.getElementsByTagName("span");
function clickListener(e) {
  e.target.parentElement.getElementsByTagName("input")[0].value = "";
}
for (let i = 0; i < spans.length; i++) {
  spans[i].addEventListener("click", clickListener);
}
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

jQuery Mobile now has this built in:

<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">

Jquery Mobile API TextInput docs

user2217751
  • 476
  • 6
  • 14
1

Something like this?? Jsfiddle Demo

    <!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    .searchinput{
    display:inline-block;vertical-align: bottom;
    width:30%;padding: 5px;padding-right:27px;border:1px solid #ccc;
        outline: none;
}
        .clearspace{width: 20px;display: inline-block;margin-left:-25px;
}
.clear {
    width: 20px;
    transition: max-width 0.3s;overflow: hidden;float: right;
    display: block;max-width: 0px;
}

.show {
    cursor: pointer;width: 20px;max-width:20px;
}
form{white-space: nowrap;}

    </style>
</head>
<body>
<form>
<input type="text" class="searchinput">
</form>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script> <script>
$(document).ready(function() {
$("input.searchinput").after('<span class="clearspace"><i class="clear" title="clear">&cross;</i></span>');
$("input.searchinput").on('keyup input',function(){
if ($(this).val()) {$(".clear").addClass("show");} else {$(".clear").removeClass("show");}
});
$('.clear').click(function(){
    $('input.searchinput').val('').focus();
    $(".clear").removeClass("show");
});
});
</script>
</body>
</html>
Toki
  • 268
  • 3
  • 10
1
<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>
Juboraj Sarker
  • 947
  • 1
  • 9
  • 13
1

You can do with this commands (without Bootstrap).

Array.from(document.querySelectorAll('.search-field')).forEach(field => {
  field.querySelector('span').addEventListener('click', e => {
    field.querySelector('input').value = '';
  });
});
:root {
  --theme-color: teal;
}

.wrapper {
  width: 80%;
  margin: 0 auto;
}

div {
  position: relative;
}

input {
  background:none;
  outline:none;
  display: inline-block;
  width: 100%;
  margin: 8px 0;
  padding: 13px 15px;
  padding-right: 42.5px;
  border: 1px solid var(--theme-color);
  border-radius: 5px;
  box-sizing: border-box;
}

span {
  position: absolute;
  top: 0;
  right: 0;
  margin: 8px 0;
  padding: 13px 15px;
  color: var(--theme-color);
  font-weight: bold;
  cursor: pointer;
}
span:after {
  content: '\2716';
}
<div class="wrapper">
  <div class="search-field">
    <input placeholder="Search..." />
    <span></span>
  </div>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

I have written a simple component using jQuery and bootstrap. Give it a try: https://github.com/mahpour/bootstrap-input-clear-button

Ehsan Mahpour
  • 131
  • 1
  • 8
0

No need to include CSS or image files. No need to include that whole heavy-artillery jQuery UI library. I wrote a lightweight jQuery plugin that does the magic for you. All you need is jQuery and the plugin. =)

jQuery InputSearch sneak peek

Fiddle here: jQuery InputSearch demo.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Glenn Mohammad
  • 3,871
  • 4
  • 36
  • 45
0

Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here: https://github.com/david-dlc-cerezo/jquery-clearField

An example of a simple usage:

<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">

<table>
    <tr>
        <td><input name="test1" id="test1" clas="test" type='text'></td>
        <td>Empty</td>
    </tr>
    <tr>
        <td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
        <td>Not empty</td>
    </tr>
</table>

<script>
    $('.test').clearField();
</script>

Obtaining something like this:

enter image description here

David
  • 4,336
  • 2
  • 23
  • 31
0

Here's a jQuery plugin (and a demo at the end).

http://jsfiddle.net/e4qhW/3/

I did it mostly to illustrate an example (and a personal challenge). Although upvotes are welcome, the other answers are well handed out on time and deserve their due recognition.

Still, in my opinion, it is over-engineered bloat (unless it makes part of a UI library).

Christian
  • 27,509
  • 17
  • 111
  • 155