我有一个文本字段和一个默认禁用的按钮。如果用户在文本字段中键入内容然后离开该字段,则该按钮应启用。
为什么我的代码没有按预期工作?这是一个 sample .
HTML
<input type="text" id="txtInput"></input>
<button class="buttEnable" disabled="disabled">Submit</button>
JS
$('#txtInput').keyup(
function()
{
if( (this).val() == '');
{
$('.buttEnable').prop('disabled', 'true');
}
else
{
$('.buttEnable').prop('disable' , 'false');
}
}
);
最佳答案
原代码有几个错误:
(this).val()
中缺少一个$
。if
条件后多了一个分号。true
和false
不应被引用。disable
在else
分支中拼写错误。
此外,如果您只想在用户离开字段时启用/禁用按钮,而不是在用户键入字符后立即启用/禁用按钮,那么您应该使用 change
而不是 键位
。
这是一个重写的版本,修复了错误并消除了一些重复代码:
$('#txtInput').change(
function()
{
var isEmpty = !$(this).val();
$('.buttEnable').prop('disabled', isEmpty);
});
更新:如果您还想在按钮启用时添加 CSS 类,您可以调用 toggleClass
:
$('.buttEnable').prop('disabled', isEmpty)
.toggleClass('buttBlue', !isEmpty);
关于javascript - 仅当文本字段包含文本时才启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343508/