提问者:小点点

js/jQuery,有没有办法用固定字符串和前导零填充我的输入文本?


我计划有一个输入文本框的前导字符串和零,最大长度为6个前导零。当用户在输入框中键入时,前导零将被擦除,直到它达到最多6个字母。初始字符串是固定的,不能擦除。

例如,

JS000000 //a fixed string (which is the letter 'JS') followed by 6 leading zeros
JS000010 //user has typed the letter '10'
JS123456 //user has typed the letter '123456' and cannot be type further

HTML

<input type="text" name="js" class="form-control" id="js_leading_zero">

JS/jQuery

$('#js_leading_zero').on('keyup', function() {
    console.log('i really have no ideas what to do here')
});

共1个答案

匿名用户

正如@rokoc.buljan所建议的,您可以在blur上更改值。一个这样的例子:

null

const inputField = document.getElementById('js_leading_zero')

inputField.addEventListener('blur', updateInput);

function updateInput(e) {
  const defaultStr = 'JS000000'
  inputField.value = defaultStr.substring(0, defaultStr.length - inputField.value.length) + inputField.value
}
<input type="text" name="js" class="form-control" id="js_leading_zero" placeholder="JS000000">