How to Put a Clear Button Inside an HTML Text Input Box

A guide on how to put a clear button inside an HTML input text box with JavaScript.

ā€¢

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.

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">&times;</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Ā &timesĀ 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.

Continue Learning

Discover more articles on similar topics