javascript - 按下回车按钮时触发显示密码功能(不应该这样做时)
问题描述
我的“showPassword”功能有问题。我有我的代码设置,因此当用户按下回车键(从技术上释放回车键)时,它将触发登录提交按钮功能。但是,我也注意到它也触发了 showPassword 函数,我不知道为什么。我对javascript相当陌生,所以任何帮助表示赞赏!
这是因为在 HTML 部分中,密码按钮位于提交按钮之前吗?
到目前为止,这是我的代码:
//Javascript event listeners:
document.addEventListener("DOMContentLoaded", function() {
loginButton.addEventListener("click", loginButtonClick);
newTransactionButton.addEventListener("click", newTransactionButtonClick);
displayPassword.addEventListener("click", displayPasswordClick);
newTransaction.addEventListener("click", newTransactionSubmitButtonClick);
next.addEventListener("click", nextPage);
prev.addEventListener("click", prevPage);
//if user wants to hit the enter key while on the username input field to submit:
var loginButtonEnter = document.getElementById("loginEmail");
loginButtonEnter.addEventListener("keyup", function(event) {
if (event.keyCode === 13) // Number 13 is the "Enter" key on the keyboard
{
document.getElementById("loginButton").click();
}
});
//if user wants to hit the enter key while on the password input field to submit:
var loginButtonEnter = document.getElementById("loginPassword");
loginButtonEnter.addEventListener("keyup", function(event) {
if (event.keyCode === 13) // Number 13 is the "Enter" key on the keyboard
{
document.getElementById("loginButton").click();
}
});
});
// Show password function:
//dispalys the password as text or hidden password (switches between)
function displayPasswordClick() {
var userPassword = document.getElementById("loginPassword");
const type = userPassword.getAttribute('type') === 'password' ? 'text' : 'password';
userPassword.setAttribute('type', type);
event.preventDefault();
}
<br>
<span class="loginBodyText">Password:</span>
<input type="password" id="loginPassword" placeholder="password"></input>
<div><b class="errorText" id="addErrorPartnerUserSecret"></b></div>
<br>
<!-- button to toggle password visibility -->
<button id="loginPasswordDisplay">Show Password</button>
<button id="loginButton">Submit</button>
解决方案
改变
<button id="loginPasswordDisplay">Show Password</button>
至
<button type="button" id="loginPasswordDisplay">Show Password</button>
元素的默认type
值为. 在表单内触发该表单中的第一个提交按钮,并且您不需要任何键盘侦听器来执行此行为。button
submit
Enter
目前那是您的Show Password按钮,因此Enter还会激活任何点击监听器。
type
按钮的默认行为。可能的值有:
submit
:按钮将表单数据提交给服务器。如果没有为与 a 关联的按钮指定属性<form>
,或者该属性为空值或无效值,则这是默认值。
reset
:该按钮将所有控件重置为其初始值,例如<input type="reset">
。(这种行为往往会惹恼用户。)
button
:按钮没有默认行为,默认按下时什么也不做。它可以让客户端脚本监听元素的事件,这些事件在事件发生时触发。
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-type
推荐阅读
- python-3.x - 如何绕原点旋转一条线?
- javascript - 防止 jQuery 突变被执行两次
- d3.js - 通过模态表单(复选框)将 SVG 下载为 PNG
- runtime-error - SAP HANA 插入表,从计算视图中选择失败
- docker-compose - 使用 docker-compose 部署 XPS 失败
- protractor - 错误:找不到模块 'protractor-multiple-cucumber-html-reporter-plugin'
- angular - Angular 6 - 将数据传递到类变量时变得未定义
- python - 将函数序列应用于python中的对象
- go - 设置环境变量 Delve
- javascript - 如何在不触发@或#等字符的情况下实现jquery自动完成