首页 > 解决方案 > 如果已经选择了用户名,如何动态禁用提交按钮?

问题描述

如果已经选择了用户名,我想使用 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)

现在它似乎正在工作。但是当我快速打字时它不起作用。有没有办法让它更好地工作?

标签: javascriptpythonflask

解决方案


条件data === true始终为假,因为类型data不是Boolean(严格比较首先检查类型是否相等)。你应该写:

if (document.querySelector('#username').value.length > 0 && data)

或使用松散相等('=='):

if (document.querySelector('#username').value.length > 0 && data == true)

甚至更好地比较:

data.length != 0

推荐阅读