JS没有从输入中获得价值

时间:2016-09-16 22:15:55

标签: javascript getelementbyid

问题是我无法获取密码字段的值 - 使用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>

2 个答案:

答案 0 :(得分: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');
    }
}

答案 1 :(得分:0)

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

相关问题