首页 > 解决方案 > 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属性)=> 单击提交而不选择单选选项不会显示任何错误。那么我该如何解决呢?

标签: javascripthtmljquery

解决方案


不确定这个d3对象来自哪里,但您的submit处理程序可能需要接受一个事件参数:

  rating_form.select('.rating-btn').on('click', function (e) {
        e.preventDefault();
        ...

有关详细信息,请参阅https://api.jquery.com/event.preventDefault/


推荐阅读