gpt4 book ai didi

javascript - 如何防止表单在提交后重新加载页面

转载 作者:行者123 更新时间:2023-11-28 17:29:55 25 4
gpt4 key购买 nike

这是我的表单代码:

<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1">
<input type="submit">
</form>

我需要使用单独的 JS 文件验证这些输入:

function getGridValues() {                                                                                                                                                
const inputHeight = document.getElementById('inputHeight').value;
const inputWidth = document.getElementById('inputWidth').value;
const colorPicker = document.getElementById('colorPicker').value;
console.log(`Height: ${inputHeight}, Width: ${inputWidth}, Color: ${colorPicker}`);
}

document.getElementById('submit').addEventListener("click", getGridValues());

问题是,每次我单击“提交”时,它都会重新加载页面并发送默认值。如果我更改值而不提交,我可以使用 JS 控制台检索这些新值。

我对此进行了很多研究,但一切都表明 jQuery/Ajax 解决方案,但我只被允许使用 HTML/CSS/JS。

有什么问题吗?我该如何修复它?

提前谢谢您。

最佳答案

使用event.preventDefault阻止submit的默认行为。然后使用ajax提交表单值。

此外,在 addEventListener 中附加事件时,您不需要立即调用 getGridValues,因此请避免在函数名称后面使用 ()

function getGridValues(e) {
e.preventDefault();
const inputHeight = document.getElementById('inputHeight').value;
const inputWidth = document.getElementById('inputWidth').value;
console.log(`Height: ${inputHeight}, Width: ${inputWidth}`);

// Here use ajax to submit the value
}

document.getElementById('submit').addEventListener("click", getGridValues);
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1">
<input type="submit" id="submit">
</form>

关于javascript - 如何防止表单在提交后重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50691455/

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