Steps for adding a delete icon to a text input field and enabling the functionality to delete text

In the code snippet below, I am creating a text input field:

<input type="text" class="signup-input text-value" name="" placeholder="e.g. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d48554c405d41486d">[email protected]</a>">

I need to incorporate a delete function that includes an "x" icon displayed at the end of the input.

Answer №1

To enhance the user experience, try utilizing the type attribute as search:

<input type="search" class="signup-input text-value" name="" placeholder="for example: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25405d4448554940655057490b464a48">[email protected]</a>">

By setting type="search", an x button will appear within the input field to clear its contents with a click.

Check out this demo on http://jsfiddle.net/rnfp59jg/

Most modern browsers support the type="search" feature, as detailed on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input:

Feature     Chrome  Firefox (Gecko) IE  Opera   Safari
type=search 5.0     4.0 (2.0)       10  11.01   (Yes)

Answer №2

If you want a seamless experience across different browsers, consider the following method:


Wrap your input in a div container and use absolute positioning to place the 'X' icon exactly where you want it on the input field.

This code snippet not only includes a smooth fading transition but also the necessary event handler:

$(document).ready(function() {

      $('.ex').click(function() {
        $('.signup-input').val("");
      });
    });
.wrap input,
.wrap .ex {
  display: inline-block;
}
.wrap {
  position: relative;
  width: 50%;
  height: 30px;
}
.ex {
  position: absolute;
  right: 0;
  top: 10%;
  height: 30px;
  width: 30px;
  opacity: 0;
  font-size: 30px;
  line-height: 30px;
  transition: all 0.8s;
  border: 1px solid transparent;
  text-align: center;
}
input {
  width: 100%;
  height: 100%;
}
.wrap input:focus ~ .ex {
  opacity: 1;
}
.ex:hover {
  border-radius: 50%;
  background: tomato;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <input type="text" id="this" class="signup-input text-value" name="" placeholder="e.g. [email protected]">
  <div class="ex">&times;</div>
</div>

Answer №3

To implement the functionality shown in the code below, you can simply integrate it into your website. The code is compatible with all web browsers.

Embed the following HTML:

<span class="surround">
    <span class="tagsh"> Name </span>
</span>

Integrate JQuery as follows:

var clearIcon ='<span id="icon_clear">X</span>';
$('<input type="input" class="textbox"/>'+clearIcon).appendTo('.surround')
    .keyup(
       function(e){
           var $dad = $($(this).parent());
           $(this).val().length>0?
               $('#icon_clear').fadeIn(300).click(function() {
                   $('.textbox').val('');}):
                   $('#icon_clear').fadeOut(300);
           if (e.keyCode in {13:"enter",32:"space"}){              
               var text = $(this).val(); 
               $('#icon_clear').remove();
               $dad.append($('<span class="tag"><span class="plus"></span><span class="minus"></span> '+text+'</span>'));
               $dad.append($(this).val("").hide().show("slow").focus());
               $dad.append(clearIcon);
           } ;});

Apply the CSS styles listed below:

.textbox{
    width:70px;
    border:1px dotted #ccc;
    margin: 0 5px;
    padding-right:18px;
}

span#icon_clear{   
    display:none;
    cursor:pointer;
    color:#38468F;
    position:relative;
    right:21px;

}
span#icon_clear:hover{
    color:#ccc;
}

For a demo and further customization options, visit the JSFiddle link provided: http://jsfiddle.net/ketan156/7PnKS/98/

Answer №4

<div class="search-wrp"><input type="text" class="signup-input text-value" name="" placeholder="e.g. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9ccd1c8c4d9c5cce9dcdbc587cac6c4">[email protected]</a>"><span class="close">x</span></div>

input{
    border: 0px;
    width: 100px;
}
.search-wrp{
    border: 1px solid #ccc;
    width: 120px;
}
.search-wrp span{
     color: blue;
     display: inline-block;
     margin-left: 5px;
     paddin: 3px; /* Note: There seems to be a typo here ('paddin' instead of 'padding') */
     cursor: pointer;

}

JS Code

$(function(){
    $(".search-wrp .close").on("click",function(){
        $(".search-wrp input").val("");
    });

});

http://jsfiddle.net/bbw99eq8/2/

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

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

What is the process for mediating a SWF-Flash file with a PHP mediating, also known as an HTTP-Pseudostreaming script?

I am currently developing a mini context media platform that utilizes HTTP Pseudostreaming. This involves using a PHP script to manage the media file, ensuring proper access and linking to the correct directory. Below are the key components of my code: // ...

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Incorporating JavaScript Variables into MySQL Database with AJAX: A Step-By-Step

Looking to implement the solution provided in this query about adding records into a database using php/ajax/mysql: Best way to add records into DB using php/ajax/mysql? This is my current code: JavaScript function FromFlash(m1, m2, m3, m4){ var po ...

Can content projection be utilized from a child component in Angular?

Keep in mind, this example could be achieved without using content projection. I am just showing a simplified version here. Imagine having a component that displays lists of names in two separate elements: import { Component } from '@angular/core&ap ...

Utilizing Discord.js to import a variable from a method in a separate file

I'm working with two commands: join and disconnect. The join command allows the bot to join a voice channel using the joinVoiceChannel method, while the disconnect command removes the bot from the channel by utilizing the getVoiceConnection method: ...

How to execute an Ajax Post request within the Django framework?

I tried setting up a basic ajax/jquery post within a django framework, but I'm struggling to figure out why the output isn't appearing on a template page. Can anyone help? When I check the content of the post in firebug's 'response&apo ...

Press anywhere outside the slide menu to close it using Javascript

Hey, I've looked around and can't find a solution to my issue. I have a javascript menu that currently requires you to click the X button to close it. I want to be able to simply click anywhere outside the menu to close it instead. <head> ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...

What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided: <html> <head> <link rel="stylesheet" type="text/css" href="CarInfoStyle.css"> </head> <script src="CarInfoJavascript.js"></script> <body> <div class="search ...

Experiencing memory issues while attempting to slice an extensive buffer in Node.js

Seeking a solution for efficiently processing a very large base64 encoded string by reading it into a byte (Uint8) array, splitting the array into chunks of a specified size, and then encoding those chunks separately. The current function in use works but ...

Tips for showing data associated with the chosen option from a dropdown list in Angular.js fetched from an API

My goal is to automatically display the coordinator's name based on the selection in a dropdown list populated with data from an API. The dropdown options are the email addresses from the JSON data below, and upon selecting a login ID, the correspondi ...

How to Detect and Toggle the Disabled Attribute in jQuery?

To target all input elements within a form, I typically use the following code snippet: var fields = $( form + " :input" ).not( "button" ); Is there a way to determine if any of these inputs have the disabled attribute set and then remove it if present? ...

The Main page is being graced by a floating Twitter Bootstrap video

When trying to display a video next to a paragraph, I encountered an issue where the paragraph was taking up 100% of the screen and the video was floating over it, obstructing part of the text. Despite setting the row and cols, the layout wasn't behav ...

Align images of varying sizes vertically within div containers, even when the image is larger than the div itself

I'm facing a challenge when it comes to aligning images vertically inside divs. The problem arises due to the following conditions: The images will have varying and unknown sizes. These images are larger than the divs they are contained in, requiri ...

Substituting Meta Viewport tag with alternative CSS method for HTML emails

In an effort to improve support for legacy Blackberrys, we made the decision to take out the meta viewport tag <meta name="viewport" content="width=device-width, initial-scale = 1.0, maximum-scale = 1.0" /> from our HTML emails. Some major email test ...