我有表单,在提交按钮上有一个单击事件监听器。单击submit按钮后,事件单击按钮上的事件侦听器就会被触发,但表单不会被提交。
这是我的密码:
<!-- 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);
});
});发布于 2018-07-26 11:52:29
禁用<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>
发布于 2018-07-26 12:03:06
正如@Zenoo所说,监听onClick-event可以防止执行实际的按钮操作(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>联署材料:
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>联署材料:
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);
});
});https://stackoverflow.com/questions/51537983
复制相似问题