gpt4 book ai didi

javascript - 如何防止表单提交

转载 作者:行者123 更新时间:2023-12-02 13:52:08 25 4
gpt4 key购买 nike

我正在使用我在另一个线程中找到的函数来阻止我的表单提交,该函数在我的笔记本电脑上工作,但是,当我将当前的更改推送到我的 gh_pages 分支以在手机上测试它时,我注意到该表单是仍在尝试提交。我目前正在这样做,因为我还没有将表单数据发送到后端,但我仍然想利用输入字段中“required”属性的功能。感谢您提前提供的任何帮助。以下是我的 .js 和 .html 文件中的相关代码:

js

document.getElementById('gameData').onsubmit = function() {
game['game'] = {};
game.game['id'] = generateId(20);
game.game['courseName'] = document.getElementById('course').value;
game.game['gameLength'] = courseLength;
game.game['players'] = {};
var participants = document.querySelectorAll('.currentPlayers');
participants.forEach(function(name){
game.game.players[generateId(5)] = name.value;
})

generateCard(game.game.gameLength)

// prevent form submission
return false;
}

表格

<form id="gameData">
<h3>What course are you playing?</h3>
<input type="text" maxlength="40" id="course" required>
<h3>How many holes are you playing?</h3>
<div class="gameLength noHiLte">
<input type="radio" name="gameLength" value="9" id="nine" checked/>
<label class="nine radio" for="nine">9</label>
<span>or</span>
<input type="radio" name="gameLength" value="18" id="eighteen"/>
<label class="radio" for="eighteen">18</label>
</div>
<div class="addPlayers">
<h3>Add up to four players:</h3><i class="fa fa-plus noHiLte" aria-hidden="true"></i>
<!-- New player Input fields generated here -->
</div>
<input type='submit' class="startGame hide" value='Tee Off!'>

最佳答案

您需要防止提交事件的 native 行为,并防止该事件冒泡或沿着捕获线继续进行。

参见this 了解详情。

下面有一个代码片段,但 Stack Overflow 不允许在其代码片段中提交表单,因此您还可以看到一个工作版本 here

为此,请在表单的提交事件处理程序中:

var form = document.getElementById("gameData"); // This is the form element
var name = document.getElementById("txtName");
var err = document.getElementById("err");

// Event handlers are automatically passed a reference to the
// event that triggered the handler. You must remember to set up
// a function argument to capture that reference. Here, that is "evt"
form.addEventListener("submit", function(evt){

// Using whatever logic you deem necessary, proceed or cancel:
if(txtName.value === ""){
// There is a problem:
evt.preventDefault(); // cancel the event
evt.stopPropagation(); // prevent it from propagating to other elements

err.textContent = "E R R O R !";
}

});
span { font-weight:bold; color: #f00;}
<form id="gameData" action="#" method="post">

Name: <input id="txtName" type="text">

<input type="submit"><span id="err"></span>
</form>

关于javascript - 如何防止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com