当单击<input type =“ submit”>元素时,jQuery .on(click)事件处理程序不会停止提交

时间:2019-07-08 15:13:13

标签: javascript jquery html

我有一个form,里面有table。该表有四个input元素,每个元素都有type=submit。该表单还具有一个隐藏的input元素。我想做的是以下事情:

当单击四个input元素之一时,将触发一个jQuery事件:

  • 停止提交
  • 将单击元素的id设置为隐藏输入的值
  • 提交表格

该事件未触发,并且正在正常提交表单。我看不出问题是什么。任何帮助表示赞赏。

<form id="myForm" method="post" action="" style="background-color: antiquewhite; margin: 0; padding: 0;">
  {% csrf_token %}
  <input type="hidden" id="op" name="op" value="">
  <table align="center" style="width: 100%;" border="1" style="background-color: antiquewhite; margin: 0; padding: 0;">
    <tr>
      <td rowspan="2">
        <h3>Is this an <i>origin</i> for the <i>claim?</i></h3>
      </td>
      <td><input type="submit" id="1" value="Yes"></td>
      <td><input type="submit" id="2" value="No"></td>
    </tr>
    <tr>
      <td><input type="submit" id="3" value="Invalid Input"></td>
      <td><input type="submit" id="4" value="Don't Know"></td>
    </tr>
  </table>
</form>
$("input").on('click', function(e) {
  e.preventDefault();
  let choice = e.target.id;
  document.getElementById("op").value = choice;
  $("#myForm").submit();
});

2 个答案:

答案 0 :(得分:1)

该行:

$("#myForm").submit();

即使您之前已禁止使用该行默认按钮单击提交,也会导致表单的提交

e.preventDefault();

答案 1 :(得分:0)

您可以创建一个类,然后将其附加到输入中

 <form id="myForm" method="post" action="" style="background-color: antiquewhite; margin: 0; padding: 0;">
  {% csrf_token %}
  <input type="hidden" id="op" name="op" value="">
  <table align="center" style="width: 100%;" border="1" style="background-color: antiquewhite; margin: 0; padding: 0;">
    <tr>
      <td rowspan="2">
        <h3>Is this an <i>origin</i> for the <i>claim?</i></h3>
      </td>
      <td><input type="text" class="custom-trigger" id="1" value="Yes"></td>
      <td><input type="text" class="custom-trigger" id="2" value="No"></td>
    </tr>
    <tr>
      <td><input type="text" class="custom-trigger" id="3" value="Invalid Input"></td>
      <td><input type="text" class="custom-trigger" id="4" value="Don't Know"></td>
    </tr>
  </table>
</form>

然后在js中获取它

$(".custom-trigger").on('click', function(e) {
   let choice = e.target.id;
   document.getElementById("op").value = choice;
  $("#myForm").submit();
});

这样做,直到您准备好所需的表单后,您才需要提交表单。