javascript - 如果已经选择了用户名,如何动态禁用提交按钮?
问题描述
如果已经选择了用户名,我想使用 javascript 动态禁用提交按钮。根据我的逻辑,我的代码应该可以工作,但事实并非如此。谁能发现我的错误?或者这不是这样做的方法吗?
Python:
@socketio.on("submit username")
def username_check(data):
if User.query.filter_by(username=data).count() == 0:
emit("username check", True, broadcast=True)
Javascript:
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// By default, submit button is disabled
document.querySelector('#submit').disabled = true;
// Enable button only if there is text in the input field
socket.on('connect', () => {
document.querySelector('#username').onkeyup = () => {
socket.emit("submit username", document.querySelector('#username').value);
};
});
socket.on('username check', data => {
if (document.querySelector('#username').value.length > 0 && data === true)
document.querySelector('#submit').disabled = false;
else
document.querySelector('#submit').disabled = true;
});
});
HTML
<form action='register' method='POST'>
<input type='text' name='username' id='username' placeholder='username'><br>
<input type='password' name='password' id='password' placeholder='password'><br>
<input type='submit' name='submit' value='REGISTER' id='submit'>
</form>
当没有输入时,我的代码似乎确实禁用了提交按钮,但在用户名已经存在时却没有。提前致谢!
编辑:我添加了
else:
emit("username check", False, broadcast=True)
现在它似乎正在工作。但是当我快速打字时它不起作用。有没有办法让它更好地工作?
解决方案
条件data === true
始终为假,因为类型data
不是Boolean
(严格比较首先检查类型是否相等)。你应该写:
if (document.querySelector('#username').value.length > 0 && data)
或使用松散相等('=='):
if (document.querySelector('#username').value.length > 0 && data == true)
甚至更好地比较:
data.length != 0
推荐阅读
- javascript - 使用 ajax 使用 php mysqli 更新模态表单上的数据
- javascript - 如何将数据附加到按钮?
- c# - C# 控件不进入方法
- php - 为什么当用户点击“发送”时没有出现任何错误但页面也没有刷新?
- java - 如何使用 Redis Spring Data 将两个值附加到一个键
- c# - 抛出异常:System.Xml.dll 中的“System.Xml.XPath.XPathException”
- python - 机器学习中的过度拟合术语
- c# - detectUrl 属性 Winforms C#
- ios - 如何使用 swift 实现带有 JSON 数据的搜索栏?
- php - 将以下基本 XML 文档转换为二维 PHP 数组