ChatGPT解决这个技术问题 Extra ChatGPT

Clear icon inside input text

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|
--------------------------------------------------
A jQuery plugin to position an image over an input box? Am I missing something or what?!
@Christian Sciberras As you can see from the answer I chose, it can be a jquery plugin...
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 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.
Folks looking for this issue will need this information as well: How do you detect the clearing of a “search” HTML5 input?

R
Roko C. Buljan

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

Older browsers

If you need IE9 support here are some workarounds

Using a standard 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; } ×

Using only a (No additional elements)

https://i.stack.imgur.com/mwIK2.jpg

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(http://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 */

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.

https://i.stack.imgur.com/mJotv.gif

Base64 string:

data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=

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 jsfiddle.net/7PnKS
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.
Nice, but the background image can clash with other CSS. The answer below by wldaunfr refers to a neat jQuery plug-in: plugins.jquery.com/clearsearch
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.
@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.
b
brasofilo

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:

Dive Into HTML 5: A form of Madness.

input type=search - search field (NEW) HTML5.


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; }
Is there a way to change the color of the X?
@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?
I think no! But I'm not a css wizard! :-(
Unfortunately this is not supported by Firefox, see : developer.mozilla.org/en-US/docs/Web/CSS/…
C
Community

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

https://i.stack.imgur.com/aAvFY.png

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; }

Always display the 'x':

×
×

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; }

Only display the 'x' when hovering over the field:

×
×

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; }

Only display the 'x' if the `input` element has a value:

×
×


K
KOGI

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


This resets the whole form, not just one field
How to hide reset image when the input is empty? Could you, KOGI give a live example?
S
Shidhin Cr

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


Excellent! Some info about browser support would be helpful.
It's broken in FF 27.0.1 for me today.
The text isn't being repositioned to make room for the 'x' button. You can't see the text behind the button.
This still clears the entire form, not just the one field.
C
Chandra Sekhar Walajapet

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/


Working in Firefox 45
Doesn't seem to be working in latest Google Chrome (v.70 ~ Nov 2018)
J
Jonathan Lonowski

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/


J
Jaspero

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.


I was meaning on the right of the input box, but inside the input itself, like google does
Use a background-image that mimics a button and use the following code <input type="text" name="Search" value="Search..." onclick="this.value='';">
this is not what I want to do: I want an icon that only if clicked clears the input....
S
Spectric

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

jQuery:

$('span').click(function(){ $('input', $(this).parent()).val(''); })

x
x
x

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); }

x
x
x


S
Suraj Rao

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

<input type="search">

u
user2217751

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


T
Toki

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>

J
Juboraj Sarker
<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>

M
Mr. Polywhirl

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'; }


C
Christian

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).


If you clear the content and start type again... there's no x button any more
hahaha looks like a 2y old bug than ;) nice to see you still around here
E
Ehsan Mahpour

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


D
David

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:

https://i.stack.imgur.com/BjlDn.png


d
double-beep

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. =)

https://i.stack.imgur.com/f5fLv.png

Fiddle here: jQuery InputSearch demo.