我正在尝试使用事件侦听器将美元符号添加到多个字段。但是,属性
th:field
将替换 input
标签中的属性值和名称。th:field
属性,它就会运行。<form id="my-Form">
<div class="form-item">
<label th:for="amount"> Amount </label>
<input th:field="${deposit.amount}" name="money_1" type="text" required>
</div>
const myForm = document.querySelector('#my-Form');
myForm.addEventListener('input', e =>
{
if ( ['money_1','money_2'].includes(e.target.name)
&& !e.target.value.startsWith('$')
){
e.target.value = "$" + e.target.value.trim();
if (e.target.value === '$')
e.target.value = '';
}
});
myForm.addEventListener('submit', e =>
{
e.preventDefault();
console.clear();
console.log('money_1 = ', myForm.money_1.value );
console.log('money_2 = ', myForm.money_2.value );
});
我建议您添加自定义属性或类来标识您要处理的字段。
然后,不要依赖名称属性,而是在事件侦听器中使用此自定义属性或类。
我对你的代码做了一些更改
<form id="my-Form">
<div class="form-item">
<label th:for="amount">Amount</label>
<input th:field="${deposit.amount}" data-money-field="true" type="text" required>
</div>
<div class="form-item">
<label th:for="otherAmount">Other Amount</label>
<input th:field="${deposit.otherAmount}" data-money-field="true" type="text" required>
</div>
<button type="submit">Submit</button>
</form>
const myForm = document.querySelector('#my-Form');
myForm.addEventListener('input', e => {
if (e.target.matches('[data-money-field]') && !e.target.value.startsWith('$')) {
e.target.value = "$" + e.target.value.trim();
if (e.target.value === '$') {
e.target.value = '';
}
}
});
myForm.addEventListener('submit', e => {
e.preventDefault();
console.clear();
const moneyFields = myForm.querySelectorAll('[data-money-field]');
moneyFields.forEach(field => {
console.log(`${field.name} = ${field.value}`);
});
});