就是这样。
我的头:
<script language="JavaScript">
function checkIt(){
var pass = document.form1.value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
window.onload = checkIt();
</script>
我的身体:
<form action="#" method="post" id="form1" onsubmit="checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
</form>
有谁能告诉我我做错了什么?它不起作用。我需要它能够比较输入值sn和var pass。
我是菜鸟而不是母语人士,所以保持冷静,请:)
答案 0 :(得分:1)
修复脚本
// to get the input value
var pass = document.getElementById("sn").value;
在您的表单上,您必须返回函数的结果
onsubmit="return checkIt();"
在您输入任何值
之前,还要删除将验证表单的window.onload = checkIt();
答案 1 :(得分:0)
尝试var pass = document.getElementById('sn').value;
答案 2 :(得分:0)
onclick="form1.submit()"
和onsubmit="return checkIt()"
答案 3 :(得分:0)
您正在调用该函数,而不是分配它
window.onload = checkIt();
需要
window.onload = checkIt;
但是你真的想在页面加载时运行验证吗?你根本不需要这一行。删除它!
您没有取消提交活动。您的函数返回true或false,但您没有处理它。
<form action="#" method="post" id="form1" onsubmit="checkIt();">
您的表单标记必须
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
注意返回声明。这将取消提交。
什么是submit()
?该页面可能会抛出一个错误,您可以在控制台中看到该错误。你需要告诉它要提交什么。这意味着引用表单。
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
您的代码中没有名为submit()
的方法。也许你想打电话给表格提交。
<img src="ok.gif" onclick="doucment.form1.submit();" style="cursor: pointer;">
使用type="image"
的输入提交表单可能会更好。
<input type="image" src="ok.gif" />
使用输入意味着不需要JavaScript来提交表单。所以删除图像标签并添加输入元素!
最后,您正在阅读表单的值,而不是输入
var pass = document.form1.value;
你想要输入!
var pass = document.form1.sn.value;
没有理由为什么1234会失败,但其他所有事情都会失败。你有逻辑错误吗?
您需要学习如何调试,使用浏览器的控制台并学习使用console.log()来查看数据。设置断点并遍历代码,以便您可以检查发生了什么。 JavaScript 101.
答案 4 :(得分:0)
尝试以下方法:
<script language="JavaScript">
function checkIt(){
var pass = document.getElementById("sn").value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
</script>
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="document.getElementById("form1").submit();" style="cursor: pointer;">
</form>