[英]Hide form after submit JQuery
我在table
内有一个html form
,我想在用户提交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
仍然可见,没有任何反应。
您必须先阻止默认操作 ,才能使用event.preventDefault()
隐藏表单
此外,如果您是在商业级别上工作,并且希望提交表单而无需重定向 ,则可以使用XHR请求
<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>
问题是选择器:
$('#form')
<form>
元素没有属性id="form"
-(即<div id="form">
-不是表单,因此不能提交)-您需要做的只是针对实际的<form>
元素。 将代码更改为此:
$('form').submit(function(e) { //NOTE: Removed "#"
e.preventDefault();
$(this).hide();
})
它将起作用:
$('form').submit(function() { $(this).hide(); })
<script src="https://code.jquery.com/jquery-3.3.1.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>
您使用的方法中存在一个问题。 每次运行时,单击页面中的“提交”按钮都会重新加载页面**单击时,这将隐藏表单,并从头开始再次渲染整个页面 。 因此,请尝试使用Ajax通过按钮而不是使用默认的表单提交方法来发送数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.