В веб-разработке обработка ввода валюты в веб-формах является распространенным требованием. Правильное форматирование ввода валюты помогает улучшить взаимодействие с пользователем и обеспечивает точный ввод данных. В этой статье мы рассмотрим различные методы форматирования ввода валюты в веб-формах на примерах кода.
Метод 1: JavaScript с маскированием ввода
<input type="text" id="currencyInput">
<script>
// Mask the input to format it as currency
const currencyInput = document.getElementById('currencyInput');
currencyInput.addEventListener('input', function (e) {
// Remove non-numeric characters
let value = e.target.value.replace(/\D/g, '');
// Format the value as currency
value = (Number(value) / 100).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
});
// Update the input value
e.target.value = value;
});
</script>
Метод 2: JavaScript с регулярными выражениями
<input type="text" id="currencyInput">
<script>
// Format the input value as currency using regular expressions
const currencyInput = document.getElementById('currencyInput');
currencyInput.addEventListener('input', function (e) {
let value = e.target.value;
// Remove non-numeric characters using regular expressions
value = value.replace(/[^0-9]/g, '');
// Add commas to separate thousands
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// Add currency symbol
value = '$' + value;
// Update the input value
e.target.value = value;
});
</script>
Метод 3: тип ввода HTML5 «число»
<input type="number" id="currencyInput" step="0.01" min="0">
<script>
// Customize the appearance of the number input
const currencyInput = document.getElementById('currencyInput');
currencyInput.addEventListener('input', function (e) {
// Format the value as currency
e.target.value = parseFloat(e.target.value).toFixed(2);
});
</script>
Метод 4: jQuery с плагином маски ввода
<input type="text" id="currencyInput">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<script>
// Apply currency formatting using jQuery Input Mask plugin
$(document).ready(function () {
$('#currencyInput').mask('000,000,000,000,000.00', {
reverse: true,
prefix: '$',
});
});
</script>
Метод 5: псевдоэлементы CSS
‘$’;
позиция: абсолютная;
отступ слева: 5 пикселей;
В этой статье мы рассмотрели несколько методов форматирования ввода валюты в веб-формах. Вы можете выбрать метод, который соответствует требованиям вашего проекта и стеку разработки. Независимо от того, предпочитаете ли вы решения на основе JavaScript, типы ввода HTML5, плагины jQuery или псевдоэлементы CSS, эти методы помогут вам улучшить взаимодействие с пользователем, обеспечив точный и визуально привлекательный ввод валюты.