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);     
    })
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...