我有最大长度=‘6’的Type=Number输入,我希望它在输入某些数字时有前导零。前导零点根据您的数字输入自动调整。
示例:当在字段中输入'12‘时,它应该添加前导零,使其变为'000012’,或者键入'123',应该是'000123',等等。
如何使用JS/JQuery实现这一点?
谢谢你的帮助。
发布于 2022-07-05 03:50:37
就像这样:
document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)
function addLeadingZero(event) {
// get maxlength attr
const maxLength = parseInt(event.target.getAttribute("maxlength"))
// "0".repeat(maxLength) <-- create default pad with maxlength given
// append zero and slice last of attr maxlength value
const newValue = ("0".repeat(maxLength) + event.target.value.toString()).slice(-maxLength);
// change the value of input
event.target.value = newValue
}<!-- @event onkeyup to make sure function run on every key up -->
<!-- @event onchange to make sure function run when we click on arrow up/down -->
<input type="number" maxlength="6">
支持负值:
document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)
function addLeadingZero(event) {
// get maxlength attr
const maxLength = parseInt(event.target.getAttribute("maxlength"))
// check and flag if negative
const isNegative = parseInt(event.target.value) < 0
// "0".repeat(maxLength) <-- create default pad with maxlength given
// Math.abs(event.target.value) to make sure we proceed with positive value
// append zero and slice last of attr maxlength value
let newValue = ("0".repeat(maxLength) + Math.abs(event.target.value).toString()).slice(-maxLength);
// add - if flag negative is true
if (isNegative) {
newValue = "-"+newValue
}
// change the value of input
event.target.value = newValue
}<!-- @event onkeyup to make sure function run on every key up -->
<!-- @event onchange to make sure function run when we click on arrow up/down -->
<input type="number" maxlength="6">
注意:虽然这个答案是正确的,更顺利的变化,请检查additional answer提供的@science乐趣使用addEventListener。
编辑:应用addEventListener。
document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)发布于 2022-07-05 04:53:05
由于我不能发表评论,我将补充一点作为答复:
最好只是监听input事件。它更平滑,在粘贴/ctrl+V时会触发。
这个答案归功于力拓。
function addLeadingZero(event) {
// get maxlength attr
const maxLength = parseInt(event.target.getAttribute("maxlength"))
// check and flag if negative
const isNegative = parseInt(event.target.value) < 0
// "0".repeat(maxLength) <-- create default pad with maxlength given
// Math.abs(event.target.value) to make sure we proceed with positive value
// append zero and slice last of attr maxlength value
let newValue = ("0".repeat(maxLength) + Math.abs(event.target.value).toString()).slice(-maxLength);
// add - if flag negative is true
if (isNegative) {
newValue = "-"+newValue
}
// change the value of input
event.target.value = newValue
}
document.querySelector("input[type=number]").addEventListener('input', addLeadingZero)<input type="number" maxlength="6">
https://stackoverflow.com/questions/72863728
复制相似问题