提交按钮上发生点击事件时,表单不会提交

时间:2018-07-26 11:41:22

标签: javascript html5 forms ecmascript-6 ecmascript-5

我有一个表单,其中“提交”按钮上有一个单击事件侦听器。单击提交按钮后,将触发按钮上的事件单击事件侦听器,但不会提交表单。

这是我的代码:

<!-- 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);
  });
});

2 个答案:

答案 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);
    });
});