Build awareness and adoption for your software startup with Circuit.

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.

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">&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