Can I change the contents of a HTML < input type='number' /> based on the value of the input?
When the input is -1 I want it to display 'unlimited'.
Run the below snippet.
For more context know that I am using Angular 7 and Angular Material.
<p>When the below input value equals -1,<br/> I would like the input to display the text 'unlimited'. <br /> Is this possible? </p>
<input type="number" min="-1" />
You can't with an input of type number
without resorting to trickery.
One way would be to resort to type="text"
and emulate what type="number"
already does so conveniently for you (allowing only numeric input, ranges, user-agent-specific UI). Usually turns out pretty messy.
Another way would be to "hide" the number input when its value is -1 and display the text "unlimited" through other means.
I did this here by placing another read-only input field underneath the number input. Other elements would work as well but another input field will give you a consistent look.
let coolInput = document.getElementById('cool-input');
// Not sure if that covers everything
coolInput.addEventListener('keyup', handleInput);
coolInput.addEventListener('change', handleInput);
coolInput.addEventListener('paste', handleInput);
function handleInput() {
if (coolInput.value == '-1') {
coolInput.classList.add('unlimited');
} else {
coolInput.classList.remove('unlimited');
}
}
form {
position: relative;
}
input[type="text"],
input[type="number"] {
color: #333;
font-size: 16px;
padding: 5px;
width: 100px;
}
#unlimited-input {
border: 1px solid #fff;
position: absolute;
z-index: -1;
}
#cool-input {
background: #fff;
border: 1px solid #999;
opacity: 1;
}
#cool-input.unlimited {
background: transparent;
color: transparent;
}
<form>
<input id="unlimited-input" type="text" readonly value="unlimited">
<input id="cool-input" type="number" min="-1" placeholder="Amount">
</form>
(JSFiddle)
Works surprisingly well. Haven't tested in IE and iOS though.