JS没有从输入中获得价值

问题描述 投票:0回答:2

问题是我无法获得我的密码字段的值 - 使用pso1的警报返回null。 我在这段代码中没有看到任何错误,所以我正在寻求帮助。

<form class='container' onsubmit="return checkit()">
    <h1> Javascript </h1>
    Login <input type='text' id='log'><br>
    Password <input type='password' id='pso1'><br>
    Confirm passwordd <input type='password' id='pso2'><br>
    <button>Register</button>
</form>

<script type="text/javascript">
    var pso1=document.getElementById('pso1').value ; 
    var pso2=document.getElementById('pso2').value ;    
    alert(pso1);
    function checkit(){
        if(pso1=!pso2){ 
            return false;
            alert('Passwords are not the same.');
        }
        else{
            return true; 
            alert('work');
        }
    }

</script>   

</body>
javascript getelementbyid
2个回答
1
投票

在您的代码中,您在页面加载之后立即设置pso1ps02的值,然后更改它们的值。您将需要更新这些值,将它们声明为函数内的局部变量:

function checkit(){
    var pso1=document.getElementById('pso1').value; 
    var pso2=document.getElementById('pso2').value;   
    if(pso1=!pso2){ 
        return false;
        alert('Passwords are not the same.');
    }
    else{
        return true; alert('work');
    }
}

0
投票

您只声明了函数checkIt。您需要调用该函数来实际检查它。

© www.soinside.com 2019 - 2024. All rights reserved.