【问题标题】:HTML form: validation and preventing page refresh when submitHTML表单:提交时验证和防止页面刷新
【发布时间】:2020-09-16 13:11:37
【问题描述】:

我有一个带有提交按钮的 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 属性)=> 在未选择单选选项的情况下单击提交将不会显示任何错误。那么我该如何解决呢?

【问题讨论】:

    标签: javascript html jquery


    【解决方案1】:

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

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

    详情见https://api.jquery.com/event.preventDefault/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 2021-07-02
    • 1970-01-01
    • 2020-06-29
    • 2016-01-18
    • 2012-09-14
    • 1970-01-01
    相关资源
    最近更新 更多