Categories
JavaScript Answers

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

Spread the love

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: .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 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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *