i want to make input percentage using javascript
<input type="text" class="form-control" id="amount" name="amount">
i made the js so when i input, it's adding %
var amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','') + '%';
})
but it still can input character, i want to only allow number 1-100, is it possible?
or maybe you have suggestion about what is better to input for percentage
HTML input type attribute allows number value so that it will only be able to accept number values.
And you can also pass a max attribute that will set a limit for entered number.
e.g.:
<input type="number" class="form-control" id="amount" name="amount" max="[YOUR_NUMBER]">
Edit: You can still validate your input with a JS function.
<input type="text" class="form-control" id="amount" name="amount">
let amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','')
let tmpValue = +amount.value
amount.value = 0 <= tmpValue <= 100 ? tmpValue + '%' : "[VALUE IF NOT 1<AMOUNT<100]";
})
A little late. This is an interesting example. One could incorporate some more logic here. The example below only allows numbers between 0 and 100 and adds the % at the end. Once you have entered a number up to max one, you have to start again. a new logic would have to be built in here.
let amount = document.getElementById('amount');
amount.addEventListener('input', function(){
const n = amount.value.replace('%','');
if ( n >= 0 && n <= 100 ) {
amount.value = amount.value.replace('%','') + '%'
} else {
amount.value = n.slice(0, -1) + '%'
}
})
<input type="text" class="form-control" id="amount" name="amount">