提交JQuery后隐藏表单

时间:2018-10-20 05:59:17

标签: javascript jquery html

我在form内有一个HTML table,我想让它在用户提交form后消失。

表格:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td colspan="3">
    <h6>Have Discount Coupon? Apply it here...</h6>
  </td>
  <td>
    <div id="form">
      <form class="coupon" method="post">
        <input type="text" name="coupon" placeholder="Enter Coupon Code" autocomplete="off">
        <input type="submit" name="coupon" value="Apply Coupon">
      </form>
    </div>
  </td>
</tr>

<script type="text/Javascript">
  $('#form').submit(function() { 
    $(this).hide(); 
  });
</script>

提交后,form仍然可见,没有任何反应。

3 个答案:

答案 0 :(得分:2)

您必须先防止默认操作,才能使用event.preventDefault()

隐藏表单

如果您是在商业级别工作,并且希望在不重定向的情况下提交表格 ,则可以使用XHR request

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td colspan="3">
    <h6>Have Discount Coupon? Apply it here...</h6>
  </td>
  <td>
    <div id="form">
      <form class="coupon" method="post">
        <input type="text" name="coupon" placeholder="Enter Coupon Code" autocomplete="off">
        <input type="submit" name="coupon" value="Apply Coupon">
      </form>
    </div>
  </td>
</tr>

<script type="text/Javascript">
  $('#form').submit(function(event) {
    event.preventDefault();
    // ... XHR request to submit form
    $(this).hide(); 
  });
</script>

答案 1 :(得分:2)

问题是选择器:

column

$('#form') 元素不具有属性<form>(即id="form"-不是表单,因此不可提交)-您需要做的只是针对实际的{{ 1}}元素。将您的代码更改为此:

<div id="form">

它将起作用:

<form>
$('form').submit(function(e) { //NOTE: Removed "#" 
    e.preventDefault();
    $(this).hide(); 
})

答案 2 :(得分:1)

您使用的方法中有一个问题。每次运行时,请单击页面中的“提交”按钮,页面将重新加载。**单击此按钮将隐藏表单,并再次从中渲染整个页面。开始。因此,请尝试使用Ajax通过按钮而不是使用默认的表单提交方法来发送数据

相关问题