输入只允许数字 1-100 javascript
input only allow number 1-100 javascript
我想使用 javascript
来输入百分比
<input type="text" class="form-control" id="amount" name="amount">
我制作了 js,所以当我输入时,它添加了 %
var amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','') + '%';
})
但是还是可以输入字符,我只想输入1-100,可以吗?
或者您可能对输入百分比有更好的建议
HTML 输入 type
属性允许 number
值,因此它只能接受数字值。
您还可以传递一个 max
属性,该属性将为输入的数字设置限制。
例如:
<input type="number" class="form-control" id="amount" name="amount" max="[YOUR_NUMBER]">
编辑:
您仍然可以使用 JS 函数验证您的输入。
<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]";
})
有点晚了。这是一个有趣的例子。人们可以在这里加入更多的逻辑。下面的示例只允许 0 到 100 之间的数字,并在末尾添加 %。一旦您输入了最大为 1 的数字,您必须重新开始。必须在此处构建新逻辑。
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">
我想使用 javascript
来输入百分比<input type="text" class="form-control" id="amount" name="amount">
我制作了 js,所以当我输入时,它添加了 %
var amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','') + '%';
})
但是还是可以输入字符,我只想输入1-100,可以吗?
或者您可能对输入百分比有更好的建议
HTML 输入 type
属性允许 number
值,因此它只能接受数字值。
您还可以传递一个 max
属性,该属性将为输入的数字设置限制。
例如:
<input type="number" class="form-control" id="amount" name="amount" max="[YOUR_NUMBER]">
编辑: 您仍然可以使用 JS 函数验证您的输入。
<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]";
})
有点晚了。这是一个有趣的例子。人们可以在这里加入更多的逻辑。下面的示例只允许 0 到 100 之间的数字,并在末尾添加 %。一旦您输入了最大为 1 的数字,您必须重新开始。必须在此处构建新逻辑。
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">