gpt4 book ai didi

Javascript:为什么我的函数没有被 onclick 调用?

转载 作者:行者123 更新时间:2023-11-28 01:05:14 26 4
gpt4 key购买 nike

我正在使用 Jscript 编写表单验证,

但我不知道为什么我什至不能通过 onclick 调用一个简单的警报功能。

这是我的部分代码

<html>
<head>
<title>Check</title>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script></head>

...

<form name="checkout" id="checkout" method="post" action="1.php">
<table align="center">
<tr>
<td>*Name</td>
<td><input type="text" name="name" id="name" size="40"/></td>
</tr>
<tr>
<td>*Phone</td>
<td><input type="text" name="phone" id="phone" size="40"/></td>
</tr>
<tr>
<td>*Address</td>
<td><textarea rows="4" cols="40" name="address"></textarea></td>
</tr>
</table>
<input type="button" value="Click me!" onclick="return displaymessage()" />
</form>
</html>

我想这个按钮应该是一个提交按钮

<input name="Submit" type="submit" value="Submit"onclick="return validate_form()"/>

但在我的测试过程中,即使是简单的“点击我!”按钮不起作用...以前会有人反驳过这样的问题吗?

最佳答案

这里有一个示例片段供您试用。

逻辑应该是:

如果验证成功,函数validate_form 应该返回true;否则为 false。如果返回值为 true,则将提交 form

var validate_form = function() {

var allGood = true; // all good if validation is successful.

// check if name is valid
allGood = document.querySelector("#name").value.length > 0;

// do other validataions... and return whether all is good
if (allGood) {
console.log("We are okay to proceed");
} else {
console.log("Please make sure the form inputs are entered to proceed");
}
return allGood;
}

var action_form = function() {
// validate form..
var isFormValid = validate_form();

// do other actions..
// ...

// submit the form...
if (isFormValid) {
console.log("submitting the form...");
document.querySelector("#checkout").submit();
}
}
<form name="checkout" id="checkout" method="post" action="https://google.com">
<table align="center">
<tr>
<td>*Name</td>
<td>
<input type="text" name="name" id="name" size="40" />
</td>
</tr>
<tr>
<td>*Phone</td>
<td>
<input type="text" name="phone" id="phone" size="40" />
</td>
</tr>
<tr>
<td>*Address</td>
<td>
<textarea rows="4" cols="40" name="address"></textarea>
</td>
</tr>
</table>
<!-- <input type="button" value="Click me!" onclick="action_form()" /> or the below -->
<input type="submit" value="Click me!" onclick="return validate_form()" />
</form>

关于Javascript:为什么我的函数没有被 onclick 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069981/

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