问题
I've found similar questions on the net, but not a viable solution to them.
My question, as the title suggests, is how could I leverage jQuery or Javascript to create a password prompt when, for example, a button is clicked.
So the following, but instead of showing the text, I'd like the text field act as a password field.
var pass1 = 'hello123';
password=prompt('Please enter password to view page')
if (password==pass1)
alert('password correct! Press ok to continue.')
I want something similar to the following image.!
回答1:
One thing you could do (like @David mentioned) is use a model window or a child window to spawn off a form to fill out.
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="prompt" value="Click for authentication prompt"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JAVASCRIPT
var theButton = document.getElementById("prompt");
theButton.onclick = function () {
var thePrompt = window.open("", "", "widht=500");
var theHTML = "";
theHTML += "<p>The server http://localhost:8888 requires a username and password. The server says: These are restricted files, please authenticate yourself.</p>";
theHTML += "<br/>";
theHTML += "Username: <input type='text' id='theUser' placeholder='Enter Username...'/>";
theHTML += "<br />";
theHTML += "Password: <input type='text' id='thePass' placeholder='Enter Password...'/>";
theHTML += "<br />";
theHTML += "<input type='button' value='OK' id='authOK'/>";
thePrompt.document.body.innerHTML = theHTML;
var theUser = thePrompt.document.getElementById("theUser").value;
var thePass = thePrompt.document.getElementById("thePass").value;
thePrompt.document.getElementById("authOK").onclick = function () {
doAuthentication(theUser, thePass);
}
}
function doAuthentication(user, pass) {
//do authentication
}
Obviously, if you're going after the same look and feel of the window you're working with, you'll want to apply some CSS and JavaScript to make it more 'pretty' so that it mirrors what you're going for.
来源:https://stackoverflow.com/questions/29403655/javascript-or-jquery-password-prompt