Sometimes, we want to add a clear button inside an HTML text input box.
In this article, weāll look at how to put a clear button inside an HTML input text box with JavaScript.
Add an input Element with Type Search
The easiest way to add an input box with a clear button is to add anĀ input
Ā element with theĀ type
Ā attribute set toĀ search
.
For instance, we can write:
<input type="search" />
Then when we type into the input box, we see the clear button displayed.
And we can click on it to clear its value.
Use CSS Styles
We can also add an input box with CSS.
For instance, we can write:
<form>
<input type="text" placeholder=" " />
<button type="reset">×</button>
</form>
Then we can style the input to add a clear button with:
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: 0.1s;
}
We select the button in the form with CSS with theĀ form button
Ā selector.
And we set itsĀ position
Ā toĀ absolute
Ā to make the button stay in place.
Then we set the width and height to fit inside the input box.
We also set theĀ background
Ā to add a background.
To add the āxā inside the button, we use theĀ ×
Ā HTML entity.
The button should haveĀ reset
Ā as the value of theĀ type
Ā attributes to clear the buttonās value when we click it.
Conclusion
The easiest way to add an input box with a clear button is to add anĀ input
Ā element with theĀ type
Ā attribute set toĀ search
.
We can also add our own CSS to our own button to add a button to clear the form input.