在JavaScript中,格式化输入框通常指的是对用户在输入框中输入的数据进行实时格式化,以确保数据符合特定的格式要求,比如电话号码、日期、货币等。以下是一些常见的方法和示例代码:
input
或keyup
事件来实时捕获用户的输入。slice
、substring
等方法用于处理字符串。<input type="text" id="phone" placeholder="Enter phone number">
<script>
document.getElementById('phone').addEventListener('input', function (e) {
let x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
</script>
<input type="text" id="date" placeholder="YYYY-MM-DD">
<script>
document.getElementById('date').addEventListener('input', function (e) {
let value = e.target.value.replace(/[^0-9]/g, '').slice(0, 8);
if(value.length > 4) value = value.slice(0, 4) + '-' + value.slice(4);
if(value.length > 7) value = value.slice(0, 7) + '-' + value.slice(7);
e.target.value = value;
});
</script>
<input type="text" id="currency" placeholder="Enter amount">
<script>
document.getElementById('currency').addEventListener('input', function (e) {
let value = e.target.value.replace(/[^0-9.]/g, '');
let parts = value.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
e.target.value = parts.join('.');
});
</script>
accounting.js
或numeral.js
。通过上述方法,可以有效地实现输入框的数据格式化,提升用户体验和应用的数据一致性。
领取专属 10元无门槛券
手把手带您无忧上云