微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – 如果输入字段为空,请禁用提交按钮

如果用户没有提供任何文本,我试图禁用提交按钮.

一见之间,它看起来一切正常,但如果用户键入一些文本,则删除它,提交按钮将启用.

这是我的代码

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val.length !=0){
            $('.sendButton').attr('disabled',false);
        }
    })
});

解决方法

您只能在document.ready上禁用,只有当DOM准备就绪时,这只会发生一次,但是当文本框为空时,您还需要在keyup事件中禁用.还要将$(this).val.length更改为$(this).val().length
$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val().length !=0)
            $('.sendButton').attr('disabled',false);            
        else
            $('.sendButton').attr('disabled',true);
    })
});

或者你可以使用条件运算符而不是if语句.还使用prop而不是attr,属性不是recommended by jQuery 1.6及以上的残疾人,检查等

As of jQuery 1.6,the .attr() method returns undefined for attributes
that have not been set. To retrieve and change DOM properties such as
the checked,selected,or disabled state of form elements,use the
07001 method,07002

$(document).ready(function(){
    $('.sendButton').prop('disabled',true);
    $('#message').keyup(function(){
        $('.sendButton').prop('disabled',this.value == "" ? true : false);     
    })
});

原文地址:https://www.jb51.cc/jquery/179709.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐