[英]Preventing form submit from reloading page
我正在尝试使表单提交数据而无需重新加载页面本身,但是目前我正在努力做到这一点。
单击当前设置中的“提交”按钮时,没有任何反应。 如果删除onsubmit="return validateForm()"
则数据将保存,但页面将重新加载。
表格HTML
<form id="predictionform-1" action="" method="post" onsubmit="return validateForm()"><p style="text-align: center;"><input type="hidden" id="_footballpool_wpnonce" name="_footballpool_wpnonce" value="f12119edf4"><input type="hidden" name="_wp_http_referer" value="/play/"><input type="hidden" name="_fp_form_id" value="1"></p><table id="matchinfo-1" class="matchinfo input"><tbody><tr><td class="matchtype" colspan="11">All</td></tr><tr><td class="matchdate" colspan="11">Dec 13, 2016</td></tr><tr id="match-5-1" class="match open" title="match 5">
</tr>
<tr><td class="score" style="width: 48%; text-align: center;"><input type="text" maxlength="3" name="_home_5" value="3" class="prediction"></td>
<td style="width: 4%; text-align: center;"></td>
<td class="score" style="width: 48%; text-align: center;"><input type="text" maxlength="3" name="_away_5" value="1" class="prediction"></td>
<td title="score" class="numeric"><span class="no-score"></span></td>
</tr></tbody></table><div class="buttonblock button-matches form-1"><input type="submit" name="_submit" value="Save"></div><input type="hidden" id="_action_1" name="_fp_action" value="update"></form>
的JavaScript
<script type="text/javascript">
function validateForm()
{
return false;
}
任何帮助都感激不尽。
谢谢
不要在onsubmit上使用HTML属性,这不是一个好习惯。
但是问题在于您必须捕获事件并阻止其默认行为,如下所示:
var form = document.getElementById("predictionform-1"); function update(){ console.log("You submited the form!"); } form.addEventListener("submit", function(event){ event.preventDefault(); update(); });
<form id="predictionform-1" action="" method="post"><p style="text-align: center;"><input type="hidden" id="_footballpool_wpnonce" name="_footballpool_wpnonce" value="f12119edf4"><input type="hidden" name="_wp_http_referer" value="/play/"><input type="hidden" name="_fp_form_id" value="1"></p><table id="matchinfo-1" class="matchinfo input"><tbody><tr><td class="matchtype" colspan="11">All</td></tr><tr><td class="matchdate" colspan="11">Dec 13, 2016</td></tr><tr id="match-5-1" class="match open" title="match 5"> </tr> <tr><td class="score" style="width: 48%; text-align: center;"><input type="text" maxlength="3" name="_home_5" value="3" class="prediction"></td> <td style="width: 4%; text-align: center;"></td> <td class="score" style="width: 48%; text-align: center;"><input type="text" maxlength="3" name="_away_5" value="1" class="prediction"></td> <td title="score" class="numeric"><span class="no-score"></span></td> </tr></tbody></table><div class="buttonblock button-matches form-1"><input type="submit" name="_submit" value="Save"></div><input type="hidden" id="_action_1" name="_fp_action" value="update"></form>
上面的表单无法提交,因为沙箱模式不允许表单提交。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.