gpt4 book ai didi

javascript - 如何防止我的表单操作 (html) 使用 javascript?

转载 作者:行者123 更新时间:2023-11-30 19:21:50 25 4
gpt4 key购买 nike

TL;DR 我只想知道如何(有条件地)停止使用 javascript 执行表单操作。

我制作了一个 html 页面,在您单击提交按钮时将您重定向到/game.html:

<form class = "initial-form" action = "/game.html">
<!--a bunch of input elements-->
<button type = "submit" value = submit id = "go-button">Go</button>
</form>

但是,我还在 html 中附加了一个脚本,用于检查输入是否有错误。理想情况下,如果输入无效,它会停止执行表单操作,但我不确定如何执行此操作。这是相关的脚本代码:

const $send = document.getElementById('go-button')

$send.onclick = ()=>{

const player = {
roomName: "",
username: ""
}

//populate player
const joinOption = document.querySelector('input[name="join-option"]:checked').value
player.roomName = $roomname.value
player.username = $username.value

socket.emit('validate-player', player, joinOption)
}

socket.on('validate-player-client', (res)=>{
console.log(res)
if(res.error){
return alert('Error: ', res.error)
}
else if (res.approved){
return alert('approved')
}
})

我知道这有点难以理解,但“验证播放器”是对后端(在节点中)的请求,以检查播放器属性是否全部有效。然后后端将发出“validate-player-client”,发送一个带有“approved”属性或“error”属性的对象。当返回具有错误属性的对象时,我想阻止表单操作导航到/game.html。我该怎么做?

谢谢大家!

最佳答案

使您的按钮不是提交按钮,并将其移到表单之外

<form class="initial-form" id="theForm" action="/game.html">
<!--a bunch of input elements-->
</form>
<button type="button" id="go-button">Go</button>

现在这段代码将提交表单 .on('validate-player-client'

const $send = document.getElementById('go-button');
// make this button NOT
const form = document.getElementById('theForm');

$send.addEventListener('click', e => {
const player = {
roomName: "",
username: ""
}
//populate player
const joinOption = document.querySelector('input[name="join-option"]:checked').value
player.roomName = $roomname.value
player.username = $username.value
socket.emit('validate-player', player, joinOption)
}

socket.on('validate-player-client', (res)=>{
console.log(res)

if(res.error){
alert('Error: ', res.error);
}
else if (res.approved){
form.submit();
}
else {
// do something else here I guess
}
})

关于javascript - 如何防止我的表单操作 (html) 使用 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368268/

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