jquery - 表单提交后HTML页面不断重置
问题描述
我有一个在本地主机上执行的简单 python 脚本和 html 代码。该代码显示一个简单的表单,允许用户填写他们的个人信息并提交。提交后,jquery 脚本会输出用户提交的任何内容。这部分代码有效。但是,输出后,表单立即重置,输出消失。在用户手动更改表单字段并重新提交之前,如何让所有内容保持不变?
Python 脚本 (app.py)
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def main():
return render_template('index.html')
if __name__ == "__main__":
app.run()
HTML 代码 (index.html)
.container{
width: 500px;
clear: both;
margin-right: auto;
margin-left: auto;
}
.container input{
width: 100%;
clear: both;
}
html, body {
margin: 0;
height: 100%;
}
br {
margin:1.25em 0;/* Firefox */
line-height:2.5em;/* chrome */
}
</style>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</header>
<body>
<h1><center>Gettin' acquainted to docker</center></h1>
<div class="container">
<form>
Salutation<input type="text" id="salutation" required><br>
First Name<input type="text" id="firstname" required><br>
Last Name<input type="text" id="lastname" required><br>
<input type="submit" id="register" class= "get_greeting" value="Display" disabled="disabled" />
<div class="results"></div>
</form>
</div>
</body>
<script>
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
$(document).ready(function(){
$('.container').on('click', '.get_greeting', function(){
$('.results').html('<p>Hi, '+$('#salutation').val()+' '+$('#firstname').val()+' '+$('#lastname').val()+'. I am learning how to implement containers...</p>')
});
});
</script>
</html>
解决方案
为了防止表单提交,您需要.preventDefault()
在submit
事件中使用:
$('form').on('submit', e => {e.preventDefault()})
如果您只想在单击按钮时阻止表单提交,则应阻止默认按钮单击:
$('button','form').on('click tap', e => {e.preventDefault()});
随意更改选择器,以便仅阻止默认操作(即在单击任何button
内部时提交表单form
)到您不想提交表单的按钮。
推荐阅读
- angularjs - JsPDF 不准确地显示表格
- angular - (单击)事件在角度 5 中的 dataTable.net 中的 FixedColumns 上不起作用
- python - Python mixin/decorator/__metaclass__ 用于基类增强
- c# - 如何更新 XAML Listview PCL?
- c# - 在程序或文档文件中存储数据有区别吗?
- android - 锁屏控件在小米设备上不起作用
- microsoft-graph-api - PATCH 带有生日或租用日期的用户请求返回 500 错误
- python - Python Django url 无法正常工作?
- javascript - 图像调整大小 - Javascript
- javascript - 重新加载视图后 Laravel AJAX 调用不起作用?