简体   繁体   English

比较表单输入值

[英]Comparing form input values

I know there are a few threads on this topic, and in fact I got my code from one such thread, but I just can't seem to get it to run. 我知道有几个关于此主题的线程,实际上我是从一个这样的线程获取代码的,但是我似乎无法使其运行。 I'm trying to compare two input boxes in an HTML form using javascript. 我正在尝试使用javascript比较HTML表单中的两个输入框。

Here is my JS: 这是我的JS:

<script>
function checkform(form1)
{
    if(form1.password.value != form1.passwordConfirm.value)
    {
        alert("Passwords must be the same");
        form1.password.focus();
        return true;
    } else {return false;}
}
</script>

Here is the HTML: 这是HTML:

<!Doctype html>
<script type="C:/wamp/www/Table/" src="javascript.js"></script>
<form name="form1" action="demo_form.asp">
    Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
    Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
    Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password        cannot be empty')"> 
    <input type="submit" value="Submit" onClick="return checkform(form1);">
</form>
</html>

Any help would be awesome! 任何帮助都是极好的!

Thanks 谢谢

Mike 麦克风

You'll need to assign an id to your form, and get that. 您需要为表单分配一个id ,然后获取该id

Replace: 更换:

<form name="form1" action="demo_form.asp">

With: 附:

<form name="form1" action="demo_form.asp" id="myForm">

And and this: 并且这个:

function checkform(form1){

With this: 有了这个:

function checkform(){
    var form1 = document.getElementById('myForm')

You also need to switch your return statements, to return false when the PW's don't match. 您还需要切换return语句,以在PW不匹配时返回false

The resulting JS / HTML: 产生的JS / HTML:

function checkform(){
    var form1 = document.getElementById('myForm');
    if(form1.password.value != form1.passwordConfirm.value)
    {
        alert("Passwords must be the same");
        form1.password.focus();
        return false;
    }
    return true;
}
<form name="form1" action="demo_form.asp" id="myForm">
    Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
    Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
    Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password        cannot be empty')"> 
    <input type="submit" value="Submit" onClick="return checkform();">
</form>

Notice how I removed the else around the second return statement. 注意如何删除第二个return语句周围的else It's not needed. 不需要

从onclick中取出return

onClick="checkform(form1);"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM