How to Integrate a Clear Button in an HTML Input Field
Written on
Chapter 1: Introduction to Clear Buttons
At times, it becomes necessary to incorporate a clear button within an HTML text input field. In this guide, we will explore how to effectively implement a clear button in an HTML input text box utilizing JavaScript.
Section 1.1: Using Input Elements with Type Search
The simplest method to introduce an input box featuring a clear button is by using an input element with its type attribute designated as "search." For example, we can create one with the following code:
<input type="search" />
When text is entered into this input box, a clear button will appear, allowing users to erase the input with a click.
Subsection 1.1.1: Visual Reference
Photo by Devon Janse van Rensburg on Unsplash
Section 1.2: Enhancing with CSS Styles
In addition to using the search input type, CSS can be utilized to create a custom input box with a clear button. Here’s an example of how to achieve this:
<form>
<input type="text" placeholder=" " />
<button type="reset">×</button>
</form>
Next, we can apply styles to the input and button as follows:
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;
}
The button is selected within the form using CSS, allowing us to position it absolutely so it remains fixed within the input field. The width and height are set to fit snugly inside the input, and the background color can be customized. The '×' character is added using the corresponding HTML entity. The button’s type is set to "reset" to ensure it clears the input value upon being clicked.
Chapter 2: Conclusion
In summary, the most straightforward approach to adding a clear button within an input box is to create an input element with a type attribute set to "search." Alternatively, custom CSS can be applied to design a clear button for our input forms.
For further insights, visit PlainEnglish.io. Subscribe to our weekly newsletter, and follow us on Twitter, LinkedIn, YouTube, and Discord. If you're interested in Growth Hacking, check out Circuit.
This video titled "Button on Input - CSS Position Tutorial" provides a visual guide on integrating CSS positions for input buttons.
In this video, titled "Add a Clear Button to MUI TextField, Input, Autocomplete, and Select," you'll learn how to effectively add clear buttons to various input types.