0

事情就是这样。

我的头:

<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 进行比较。

我是菜鸟,不是母语人士,所以请保持冷静:)

4

5 回答 5

1

修复你的脚本

// to get the input value
var pass = document.getElementById("sn").value;

在您的表单上,您必须返回函数的结果

onsubmit="return checkIt();"

在您输入任何值之前,还要删除window.onload = checkIt();将验证表单的内容

于 2013-06-04T16:43:08.370 回答
0

尝试var pass = document.getElementById('sn').value;

于 2013-06-04T16:41:39.517 回答
0

onclick="form1.submit()"onsubmit="return checkIt()"

于 2013-06-04T16:48:40.247 回答
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;">

您最好使用 input withtype="image"来提交表单。

<input type="image" src="ok.gif" />

使用输入意味着提交表单不需要 JavaScript。所以删除图像标签并添加输入元素!


最后,您正在阅读表单的值,而不是输入

var pass = document.form1.value;  

你想要输入!

var pass = document.form1.sn.value;  

为什么 1234 会失败是没有意义的,但所有其他事情都会过去。你没有逻辑错误吗?

您需要学习如何调试、使用浏览器的控制台并学习使用 console.log() 来查看数据。设置断点并遍历代码,以便检查发生了什么。JavaScript 101。

于 2013-06-04T16:48:46.777 回答
0

尝试以下操作:

Javascript

<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>

HTML

<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>
于 2013-06-04T16:59:10.327 回答