使用密码对话框Javascript请求帮助

Requring assistance with a password dialog box Javascript

本文关键字:请求 帮助 Javascript 对话框 密码      更新时间:2023-09-26

我需要制作一个密码对话框,告诉您输入密码,然后输入后显示一个提示对话框,提示您输入了密码,并以星号和普通文本显示您的密码。我有这一点,但如果我的密码包含空格,我需要它来防止我输入密码。例如,比尔·盖茨不应该工作。有人能帮我吗?这就是我目前所拥有的。

<html>
<head>
<title> Password Alert Box</title>
<script type="text/JavaScript">
//declared variables
var input1 = 0;
input1=prompt("Please enter your Password here","Enter Password Here");//made a prompt box to enter the password
var asterisks = (new Array(input1.length+1).join("*"));//converts the password string into asterisks
window.alert("Valid password "+ asterisks + "'n You entered the password " + input1); //outputs the message valid password, along with the string entered in asterisks, also outputs the password in plain text
</script>
</head>
<body>
</body>
</html>

尝试此代码

function psw() {
    var input1 = prompt("Please enter your Password here","Enter Password Here");
    if(input1.indexOf(" ") > 0) {
        alert('error can not contain spaces');
        psw();
        return false;
    }
    var asterisks = (new Array(input1.length+1).join("*"));
    alert("Valid password "+ asterisks + "'n You entered the password " + input1);
}
psw();

注意:我使用了indexOf,它与IE9+一起工作

演示

一个对话框。如果您使用密码,我会避免使用提示,因为它不如'<input type="password" />'安全。这意味着您将无法使用提示。考虑以下内容:

HTML:

<div style="display: none;" id="alert">
    <form>
        <input id="password" type="password" name="password" placeholder="password here" />
        <input id="submit" type="submit" value="Submit" />
    </form>
</div>
<button id="show">Show</button>

JS:

var pass = document.getElementById('password');
pass.onkeyup = function (e) {
    var key = e.keyCode;
    if (key == 32) {
        //spacebar -- so lets clear what has currently been written
        this.value = "";
        alert('Spaces are not allowed, please try again');
    }
}
document.getElementById('show').onclick = function () {
    document.getElementById('alert').style.display = 'block';
}
document.getElementById('submit').onclick = function (e) {
    e.preventDefault();
    alert(pass.value + ' ... ' + (new Array(pass.value.length + 1).join("*")));
}

CSS:

#alert {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1000;
    background-color: red;
    padding: 30px;
}

在这里,我们创建了一个"浮动"框(类似于jQuery中的对话框/模式)。在这个盒子里,你会发现我之前在表格中提到的输入类型密码

对于您的情况,您不需要将表单发送到php文件中进行处理,所以您只需截取表单并在警报中显示密码值。

演示

更新时,可以在密码值更改之前拦截空格键,而不执行任何操作。例如,您可以使用onkeyup事件并复制相同的代码。如果检测到空格键,您所需要做的就是e.preventDefault();,并且空格键不会添加到您的密码值中。

DEMO2,其中空格键没有添加到密码