javascript - HTML表单:提交时验证和防止页面刷新
问题描述
我有一个带有提交按钮的 HTML 表单,并希望在单击提交后阻止页面刷新(我在单击处理程序中也有一些 AJAX 调用):
var rating_form = d3.select("body")
.append('form')
.attr('class', 'rating');
// Appending up and down vote radio button
var radio_groups = rating_form.append('div').attr('class', 'form-group');
// Radio for up
var radio_grp_chk = radio_groups
.append('div')
.attr('class', 'form-check form-check-inline upvote');
radio_grp_chk
.append('input')
.attr('class', 'form-check-input')
.attr('type', 'radio')
.attr('name', 'voting-radio')
.attr('value', 'thumbup')
.attr("required", "");
radio_grp_chk.append('span').text("upvote");
// Radio for down
var radio_grp_chk2 = radio_groups
.append('div')
.attr('class', 'form-check form-check-inline downvote');
radio_grp_chk2
.append('input')
.attr('class', 'form-check-input')
.attr('type', 'radio')
.attr('name', 'voting-radio')
.attr('value', 'thumbdown')
.attr("required", "");
radio_grp_chk2.append('span').text("downvote");
// Appending text area
rating_form
.append('div')
.attr('class', 'form-group')
.append('textarea')
.attr('class', 'form-control feedback-text')
.attr('placeholder', 'Enter your text...');
// Submit button
rating_form
.append('button')
.attr('type', 'submit')
.attr('class', 'btn btn-primary rating-btn')
.text('Submit!');
// Bind click event
rating_form.select('.rating-btn').on('click', function () {
d3.event.preventDefault();
var current_text = $("form").find("textarea").val();
var current_vote = $("form").find('input[name=voting-radio]:checked').val()
console.log(
'My text is: ' +
current_text +
" and the vote is: " +
current_vote
);
// Some further AJAX calls here
});
<!DOCTYPE html>
<head>
<!-- bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
crossorigin="anonymous">
</head>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.0.min.js" crossorigin="anonymous"></script>
</body>
为了防止提交时自动刷新,我d3.event.preventDefault();
在点击监听器中使用。
但是,这会使表单无法验证(我的单选按钮具有required
属性)=> 单击提交而不选择单选选项不会显示任何错误。那么我该如何解决呢?
解决方案
不确定这个d3
对象来自哪里,但您的submit
处理程序可能需要接受一个事件参数:
rating_form.select('.rating-btn').on('click', function (e) {
e.preventDefault();
...
推荐阅读
- reactjs - 如何从材料 ui 提交自动完成的值?
- pine-script - Metastock 脚本到 Pine (Tradingview)
- c++ - [decl.constexpr].5 到底是什么意思?
- discord - Discord Bot UnhandledPromiseRejectionWarning:TypeError:generalChannel.send 不是函数
- excel - VBA打印循环没有将整个循环写入批处理文件
- c# - 在不同的单元格值之间插入行
- markdown - 块引号未在 readme.md 中正确呈现
- google-sheets - 谷歌工作表从多个工作表导入给出错误
- android - Android中的@PrimaryKey注释字段不被视为单独的字段吗?
- r - 网页在浏览器中工作,但不是来自 R:SSL 证书问题:证书已过期