gpt4 book ai didi

javascript - 表单 onclick 不起作用

转载 作者:行者123 更新时间:2023-11-28 18:01:51 25 4
gpt4 key购买 nike

我目前正在学习 JS,并尝试创建一个验证函数来查看字段是否为空。当我单击“提交”按钮时,我希望在 Chrome 的 JS 控制台中看到一些内容,但没有看到任何内容。为什么这不会将任何内容回显到控制台中?

var field1 = document.getElementById("field1");
var field2 = document.getElementById("field2");
var submitBtn = document.getElementById("submitBtn");

function validate() {

if(field1 === "" || field2 === "") {
console.log("Make sure all fields have been filled out correctly");
} else {
console.log("they are full");
}
}


<form action="" action="get">
<input type="text" id="field1" name="field1" autocomplete="off" placeholder="Enter something"/>
<input type="text" id="field2" name="field2" autocomplete="off" placeholder="Enter that thing again"/>
<input type="submit" id="submitBtn" name="submitBtn" value="Submit" onclick="return validate()" />
</form>

最佳答案

如果您不提交表单,只需将其设为按钮而不是提交。Submit 使表单被提交

请检查以下代码片段

var submitBtn = document.getElementById("submitBtn");

function validate() {
var field1 = document.getElementById("field1").value;
var field2 = document.getElementById("field2").value;
if (field1 === "" || field2 === "") {
console.log("Make sure all fields have been filled out correctly");
} else {
console.log("they are full");
}
}
<form action="" action="get">
<input type="text" id="field1" name="field1" autocomplete="off" placeholder="Enter something" />
<input type="text" id="field2" name="field2" autocomplete="off" placeholder="Enter that thing again" />
<input type="button" id="submitBtn" name="submitBtn" value="Submit" onclick="return validate()" />
</form>

希望对你有帮助

关于javascript - 表单 onclick 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401609/

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