2014-11-21 34 views
1

我正在做一个客户端在JavaScript和HTML。我有个问题。我想检查密码和重复密码是否相同。在这种情况下,我想禁用输入。我看到了一些代码,但我不明白为什么它不起作用。你可以帮我吗? 这里是我的HTML:使用javascript禁用输入。检查代码

<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password"> 
<input class="btn btn-beats btn-block btn-stacked" value="Sign up" onkeydown="enable()" id = "btnPlaceOrder" type="submit"> 
<input class="form-control form-stacked" name="password" id = "password" placeholder="Password" type="password" required="true"> 

然后这里是我的javascript函数:

var password = document.getElementById("password"); 
var repeat = document.getElementById("repeat"); 
    function enable(){ 
     if (password.value() == repeat.value()){ 
     document.getElementById("btnPlaceOrder").disabled = false; 
     } else{ 
     document.getElementById("btnPlaceOrder").disabled = true; 
     } 
} 

只是要精确,我做的JavaScript的进口在我的HTML

+4

'value'是一个属性,而不是一个方法,所以'if(password.value == repeat.value)' – pawel 2014-11-21 09:26:40

+0

ok。点更多@pawelbut它仍然不起作用 – pp94 2014-11-21 09:27:35

+1

这是什么意思@dystroy? – pp94 2014-11-21 09:27:54

回答

3

HTML: 将侦听器添加到密码输入中,因此提交按钮填充会根据用户输入更改其状态。

<input id="password" type="password" onkeyup="enable()"> 
<input id="repeat" type="password" onkeyup="enable()"> 
<input value="Sign up" id="btnPlaceOrder" type="submit"> 

JS

function enable(){ 
    // the comparison returns true or false so no need for if/else 
    document.getElementById("btnPlaceOrder").disabled = password.value !== repeat.value; 
} 

小提琴:http://jsfiddle.net/40vvL1em/

+0

令人惊叹。谢谢你(对不起,我有密码功能和重复功能) – pp94 2014-11-21 09:36:33

+0

抱歉,但我必须等待2分钟(不知道为什么),以确认您的答案是正确的... ... – pp94 2014-11-21 09:38:32

1

那么简单的调用函数在onkeyup()事件的重复投入。

<input class="form-control form-stacked last" name="repeatPassword" id="repeat" placeholder="Repeat password" type="password" onkeyup="enable()"> 

而这里的JS功能:

var password = document.getElementById("password").value; 
var repeat = document.getElementById("repeat").value; 
function enable(){ 
if (password === repeat){ 
    document.getElementById("btnPlaceOrder").disabled = false; 
} 
else{ 
    document.getElementById("btnPlaceOrder").disabled = true; 
} 
} 

应该这样做。

+0

谢谢@chsdk我已经使用pawel解决方案 – pp94 2014-11-21 09:37:26

+0

好吧,他的JS方法更好,但我认为你不必在密码输入键入事件中调用'enable()'? – 2014-11-21 09:40:52

+0

绝对我不想说你的问题不是更好。我会检查你的解决方案 – pp94 2014-11-21 09:45:01