Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box?

I've searched, but I could only find instructions for placing an icon as the background of the input element. Is there a jQuery plugin or any other solution available?

I am looking for a way to incorporate the clear icon inside the input text element, like this:

--------------------------------------------------
|                                               X|
--------------------------------------------------

Answer №1

To enhance your input field, consider adding a type="search"
Although the support is good, please note that it won't function in IE versions less than 10.

<input type="search">


For Older Browsers

If you require support for IE9, here are some alternatives:

Option 1: Using a standard
<input type="text">
with additional HTML elements:

// JavaScript code to implement 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");
  });
  
});
/* CSS style for 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 default 'X' icon from IE */
  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>

Option 2: Utilizing only
<input class="clearable" type="text">
without additional elements

To implement this option, apply the class="clearable" to your input and customize its background image accordingly:

// JavaScript code for implementing 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 local storage or server
/* CSS styles for clearable text inputs */
.clearable{
  background: #fff url(https://i.sstatic.net/mJotv.gif) no-repeat right -10px center;
  border: 1px solid #999;
  padding: 3px 18px 3px 4px; /* Make sure right padding (18) matches with jQuery setting! */
  border-radius: 3px;
  transition: background 0.4s;
}
.clearable.x  { background-position: right 5px center; } /* Show icon using jQuery */
.clearable.onX{ cursor: pointer; } /* Provide hover cursor effect via jQuery */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove default 'X' icon in IE */
<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 key approach here involves applying some right padding (e.g., 18px) to the input, moving the background-image out of sight to the right (e.g., right -10px center). This padding ensures that text does not hide under the icon when visible. Using jQuery, the class "x" will be added if there's content in the input, showing the clear icon. To further refine functionality, utilize jQuery to target inputs with class x, determine during mousemove whether the mouse is inside the 18px "x" region, add the class onX accordingly. Clicking on the onX class removes all classes, resets the input value, and hides the icon.


Gif dimensions: 7x7 pixels

Base64 string of the GIF:

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

Answer №2

May I propose using the following code if you are comfortable with limiting this to HTML 5 compliant browsers:

<input type="search" />

Check out the JS Fiddle demo here

It should be noted that in Chromium (Ubuntu 11.04), there needs to be text inside the input element for the clear-text image/functionality to appear.

For more information, you can visit:

Answer №3

Based on information from MDN, it is stated that

<input type="search" />
is currently compatible with all modern web browsers:

https://i.sstatic.net/aAvFY.png

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


Nevertheless, if you seek a consistent behavior across different browsers, here are some lightweight alternatives that solely rely on JavaScript:

Option 1 - Maintain the 'x' always visible: (see 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>Keep displaying 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 - Display the 'x' only when hovering over the field: (see 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>Show the 'x' only upon hovering:</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 - Show the 'x' only when the input element contains text: (see example here)

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

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

  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>Display the 'x' only if the `input` field has content:</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>

Answer №4

To create a reset button styled with an image, you can...

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="enter text here" />
   <input type="reset" value="" alt="clear input" />
</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>

View the functioning example at this link: http://jsbin.com/uloli3/63

Answer №5

After finding that none of the existing solutions met our needs, we took matters into our own hands and created a simple jQuery plugin called jQuery-ClearSearch -

Implementing it is straightforward:

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

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

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

Answer №6

If you're striving for a Google-like design, keep in mind that the "X" is not actually placed within the <input> element itself. Instead, they are positioned next to each other with the outer container designed to give the illusion of being part of the text box.

Your HTML markup should look like this:

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

For styling, apply the following CSS rules:

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

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

You can see an example implementation here: http://jsfiddle.net/VTvNX/

Answer №7

Update the input box to be of type 'search' either in design mode or

<input type="search">

Answer №8

UPDATE: Came across this helpful resource. Check it out here:

If you're looking to position the clear button on the right side of the input field, one effective method is to add an image next to the input box. While using a background image could work for something inside the box, implementing a script to clear the text may prove challenging.

To achieve this functionality, simply insert an image and incorporate JavaScript code to enable clearing of the textbox content.

Answer №9

Utilize basic absolute positioning - it's a simple technique.

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>

Answer №10

One of the latest features in jQuery Mobile is the addition of:

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

Check out the Jquery Mobile API TextInput documentation for more information.

Answer №11

Is this what you're looking for? Check out the Jsfiddle Demo here

    <!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>

Answer №12

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

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

   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: 40px;
      width: 40px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -10px;
      left: -45px;
   }
</style>

Answer №13

Below are some commands you can use (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>

Answer №14

Introducing a new jQuery plugin with a demo included for your convenience.

Check out the demo here

I created this plugin as a personal challenge and to provide an example for others. While I appreciate any upvotes, I believe other answers also deserve recognition for their timely contributions.

In my view, this plugin may seem unnecessarily complex unless it serves a specific purpose within a UI library.

Answer №16

After modifying a jquery plugin to suit my specific requirements and adding personalized features, I was able to create a new plugin. For the modified version, visit: https://github.com/david-dlc-cerezo/jquery-clearField

Here is an instance of its basic 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>

This results in something like the following:

Answer №17

Forget about the hassle of including CSS or image files. No need to weigh down your project with the bulky jQuery UI library. I've created a streamlined jQuery plugin that will work its magic for you effortlessly. Just grab jQuery and the plugin, and you're good to go! =)

https://i.sstatic.net/f5fLv.png

Check out the live demo on Fiddle: jQuery InputSearch demo.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining arrays of objects in VueJS

I am working with 2 components: parent component (using vue-bootstrap modal with a vue-bootstrap table) child component (utilizing vue-bootstrap modal with a form) Issue: When I submit the form in the child component, it successfully adds the object to ...

Having issues with Vue.js v-repeat not displaying any content

I have just started learning about vue.js. I attempted to display a simple list, but it is not showing anything. Here is my code: <html> <head> <title>VUE Series</title> <link rel="stylesheet" type="text/css" ...

Having trouble retrieving state parameters when trying to launch a modal in AngularJS

When the "view detail" link is clicked, I wanted to open a modal for a detailed view of a specific user. However, I encountered an issue where I couldn't retrieve the user ID in the resolve attribute of $uibModal.open(). Strangely enough, the ID is av ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

Accomplishing Nested Element Retrieval in Javascript

While this question may have been asked previously, it hasn't been tackled quite like this before... I have the following block of HTML code. <table class="fr ralign cartSummaryTable"> <tr> <td width="320px"> <div cl ...

What is the best way to implement dragging functionality for an image within a specific area?

Here's a snippet of the code I'm working with: link This is the HTML code: <div class="border"> <div id="i-choose"> <input type="file" name="file" id="file" class="inputfile"> <label for="file"& ...

Leveraging the power of jQuery/javascript in conjunction with Google Forms

Currently, I am attempting to utilize jQuery and JavaScript with an iframe that contains a Google form. The code snippet is displayed below: <body> <iframe id="myFormFrame" src="https://docs.google.com/forms/d/smfjkafj809890dfafhfdfd/viewform?emb ...

Trying to reduce the cursor box area within an A link containing a div box

My communication skills are lacking, so I have included an image to better illustrate my issue. Here is the problem .body { text-align: center; display: flex; flex-direction: column; align-items: center; } .flex-container { display: flex; ...

Can a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file: $('#form-name').submit(function(ev ...

Expand the initial expansion panel within an Angular Material accordion by opening the first attachment

In Angular Material expansion panels, the expanded input can be used to automatically open a specific panel when the page loads. However, in my dynamic accordion where all panels are optional, I want the first panel to be opened by default. I could manual ...

Error: The method api.createContextKey is not defined while running the Next.js development server

I am currently facing an issue while attempting to start the development server for my Next.js project. The problem arises when I try to incorporate MUI into my project, resulting in these specific errors. The error message points to a TypeError related to ...

What is the best method to identify false values within the properties of a series of interconnected objects?

I am currently utilizing the Logical OR (||) operator to verify and assign values if they are not falsy in the following manner: let locationDistrict = result.results[0].address_components[2].long_name || result.resu ...

Using Bootstrap to create a floating image amidst surrounding elements

<div id="wrapper"> <div class="row"> <div class="col-sm-6 col-xs-12 image">Image</div> <div class="col-sm-6 col-xs-12 title">Title</div> <div class="col-sm-6 col-xs-12 description"> Desc ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Moving elements using jQuery UI Drag/Drop feature and snapping them to the bottom position

After exploring this informative answer, I have managed to create a group of draggable divs that can snap into place. However, an issue I am facing is that these draggable divs have varying heights, and I require them to always snap to the bottom of the ta ...

Is it possible to create Excel documents containing statistical graphs and pie charts by utilizing PHP and SQL?

I have a database filled with statistical data that I want to export into an excel file. Can anyone recommend any popular libraries or scripts for generating excel files? Additionally, I am interested in displaying some of the dry numerical data in p ...

Having difficulties with Vue components displaying in Laravel's blade.php file

Let me share my current setup with you: This is the main "Welcome.blade.php" file where I have included relevant information as the file is quite lengthy: <div id='app'> <router-view></router-view> </div> <script src ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...