我有一个表单,其中“提交”按钮上有一个单击事件侦听器。单击提交按钮后,将触发按钮上的事件单击事件侦听器,但不会提交表单。
这是我的代码:
<!-- HTML -->
<form action="/customer/create" method="post">
<input type="text" name="email">
<button type="submit" class="has-button-spinner">Create Customer</button>
</form>
<!-- JS -->
const buttons = document.querySelectorAll('.has-button-spinner');
buttons.forEach((button) => {
button.addEventListener('click', (e) => {
const target = e.currentTarget;
target.classList.add('is-loading');
target.setAttribute('disabled', true);
});
});
答案 0 :(得分:4)
禁用<button>
时,将阻止其执行(提交表单)。
不监听按钮的click
事件,而是监听表单的submit
事件:
const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', (e) => {
const target = form.querySelector('button.has-button-spinner');
target.classList.add('is-loading');
target.setAttribute('disabled', true);
});
});
<form action="/customer/create" method="post">
<input type="text" name="email">
<button type="submit" class="has-button-spinner">Create Customer</button>
</form>
答案 1 :(得分:1)
正如@Zenoo所说,监听onClick
事件会阻止执行实际的按钮动作(submit
),因此您可以:
HTML:
<!-- add id to form -->
<form id="form_create_customer" action="/customer/create" method="post">
<input type="text" name="email">
<button type="submit" class="has-button-spinner">Create Customer</button>
</form>
JS:
const buttons = document.querySelectorAll('.has-button-spinner');
buttons.forEach((button) => {
button.addEventListener('click', (e) => {
const target = e.currentTarget;
target.classList.add('is-loading');
target.setAttribute('disabled', true);
document.getElementById("form_create_customer").submit();
});
});
onSubmit
而不是onClick
:HTML:
<!-- add id to form -->
<form id="form_create_customer" action="/customer/create" method="post">
<input type="text" name="email">
<button type="submit" class="has-button-spinner">Create Customer</button>
</form>
JS:
const buttons = document.querySelectorAll('.has-button-spinner');
buttons.forEach(button => {
button.parentNode.addEventListener('submit', e => {
// we're not using the event data to avoid
// having to find the button from the form
// on each submit event
button.classList.add('is-loading');
button.setAttribute('disabled', true);
});
});