murday1983
murday1983

Reputation: 4016

Is there a way to clear an input type="number" like when using type="search"

I have a Bootstrap 4 form with various inputs on some number, some text and others email.

I have already sorted my text inputs by adding the below, which is displaying the 'x' in the input

input[type="search"]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

But I want the same for my 'number' and 'email' inputs

I tried using the below to see if it works, but it doesn't

input[type="search"]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

I have also used the below CSS to remove the arrows when using type='number' and again it works fine

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

Thought I'd ask before I revert to using regex for my number inputs

enter image description here

HTML

<input id="one" class="form-control" type="search" value="Test company name" />
<input id="two" class="form-control" type="number" value="123456" />
<input id="two" class="form-control" type="number" value="12345634" />

As you can see the arrows are not displaying for my number inputs which is what I want.

Upvotes: 1

Views: 605

Answers (1)

TimonNetherlands
TimonNetherlands

Reputation: 1053

There is good and bad news. The bad news first: the webkit cancel button is only available to input fields of type search.

The good news: you can create the button yourself.

Copy and paste the following CSS:

.close-button {
  color: #1e52e3;
  font-size: 12pt;
  font-family: monospace,sans-serif;
  font-weight: 600;
  position: absolute;
  z-index: 2;
  display: none;
}

.close-button:hover {
  cursor: pointer;
}

and change the font-size to what is suitable by trial and error.

Then add this Javascript before the </body> tag in the relevant HTML:

<script>
var fields = document.querySelectorAll('input[type=number],input[type=email]');

fields.forEach(function(input) {
  let x = document.createElement('span');
  x.classList.add('close-button');
  x.innerHTML = 'x';
  x.style.left = input.clientWidth - 15;
  x.onmousedown = removeContent;
  input.parentNode.insertBefore(x, input);
  input.oninput = toggleCloseButton;
  input.addEventListener( 'focusin', toggleCloseButton);
  input.addEventListener( 'focusout', hideCloseButton);
});

function toggleCloseButton() {
   if (this.value.length > 0) {
     this.previousSibling.style.display = 'block';
   } else {
     this.previousSibling.style.display = 'none';
   }
}

function hideCloseButton() {
  this.previousSibling.style.display = 'none';
}

function removeContent(){
  this.nextSibling.value = '';
  this.nextSibling.focus();
}
</script>

Upvotes: 1

Related Questions