gpt4 book ai didi

验证表单时 Javascript 函数运行两次

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

我确信对此必须有一个简单的解释。我试图在选择“未选择”选项(我相信默认情况下已选择)时显示“必须选择国家/地区”警报,然后单击验证按钮。我已经能够正确显示警报的功能,但问题是警报显示两次。

为什么警报显示两次,如何让它只显示一次?谢谢!

function CountrySelectValidation() { // ensures country is selected
var ValidateCountry = document.forms["registration-form"]["Country"].value;
if (ValidateCountry == "not-selected") {
alert("Country must be selected");
return false;
} else {
return true;
}
}

function SubmitForm() {
if (CountrySelectValidation()) {
// check if true, then execute this code
document.getElementById("registration-form").submit();
}
}
<form id="registration-form">
What country are you from?
<select name="Country">
<option value="not-selected">Not Selected</option>
<option value="england">England</option>
<option value="wales">Wales</option>
<option value="scotland">Scotland</option>
<option value="northern-ireland">Northern Ireland</option>
</select>
<br><br><input type="submit" value="Submit Method 1">
<button type="reset">Reset Method 1</button>
<button type="submit" id="submit-2">Submit Method 2</button>
</form>

<button onClick="ResetForm()">Reset Method 1</button>
<button onClick="CountrySelectValidation(); SubmitForm()">Validation</button>

最佳答案

CountrySelectValidation()
...
if (CountrySelectValidation())

您在 if 中运行 CountrySelectValidation 函数(它实际执行),因此这就是它运行两次的原因。

关于验证表单时 Javascript 函数运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017657/

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