如果输入字段为空,则禁用提交按钮 [英] If input field is empty, disable submit button
问题描述
如果用户没有提供任何文本,我试图禁用提交按钮。
乍一看,它看起来一切正常,但如果用户键入一些文本,然后删除它,则提交按钮变为启用。
以下是我的代码:
$(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 作为属性,而不是由jQuery 1.6推荐及以上版本禁用,选中
$ b
从jQuery 1.6开始,对于尚未设置的属性
,.attr()方法返回undefined。要检索和更改DOM属性(如
)表单元素的checked,selected或disabled状态,请使用
。 prop()方法, jQuery文档
$(document).ready(function(){
$('。sendButton')。prop('disabled',true);
$('#message')。keyup(function(){
$('。sendButton')。prop('disabled',this.value ==?true:false);
})
});
I'm trying to disable submit button if the user hasn't provided any text.
At first sight it looks that everything works just fine, but if user types some text, then deletes it, the submit button becomes enabled.
Here is my code:
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val.length !=0){
$('.sendButton').attr('disabled', false);
}
})
});
You are disabling only on document.ready
and this happens only once when DOM
is ready but you need to disable
in keyup event too when textbox gets empty. Also change $(this).val.length
to $(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);
})
});
Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.
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 .prop() method, jQuery docs
$(document).ready(function(){
$('.sendButton').prop('disabled',true);
$('#message').keyup(function(){
$('.sendButton').prop('disabled', this.value == "" ? true : false);
})
});
这篇关于如果输入字段为空,则禁用提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!