我有一个“发布”按钮,当在文本区域中输入文本时,该按钮会激活(从模糊变为彩色,从禁用变为启用)。
这工作正常,但我希望文本区域能够检测文本区域中何时没有任何内容。假设我在文本区域中输入了“abc”..提交按钮将变为事件状态,但假设我现在删除了所有文本..该按钮仍然处于事件状态..但并不完全,因为我有这个:
commentButton.prop({ disabled: commentBox.val() == 0 });
这会阻止表单在文本区域中没有任何内容的情况下提交。问题是提交按钮仍然是彩色的,并且没有按预期返回到模糊的非事件状态。
这让我想到了我的问题..
我可以设置一些东西,当我将注意力集中在文本区域并输入时,它就会激活并开始监听,并知道我何时删除了文本区域中的所有内容?
通过这种方式,我可以设置一个 if 语句来说明如果文本全部删除,则为彩色状态按钮设置removeClass,为模糊状态按钮设置addClass。
这也应该适用于空白。
这是我当前的代码:
.comment_box = 我的文本区域
.activeCommentButton = 彩色提交按钮
.commentButton = 模糊的提交按钮
$(".microposts").off().on("focus", ".comment_box", function () {
$(this).prop("rows", 7);
$(this).parent().find(".activeCommentButton").removeClass("activeCommentButton").addClass("commentButton");
var commentBox = $(this),
form = $(this).parent(),
cancelButton = form.children(".commentButtons").children(".cancelButton"),
commentButton = form.children(".commentButtons").children(".commentButton");
$(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();
form.children(".commentButtons").addClass("displayButtons");
commentButton.prop({
disabled: true
});
commentBox.off().on("keyup keypress input change", function () {
commentButton.prop({
disabled: commentBox.val() == 0
});
commentButton.removeClass("commentButton").addClass("activeCommentButton");
});
cancelButton.click(function () {
commentBox.removeClass("comment_box_focused").addClass("comment_box");
form.children(".commentButtons").removeClass("displayButtons");
commentBox.val("");
});
});
亲切的问候
最佳答案
是的,试试这个,你可以修改它:
$(".commentButton").prop({ disabled: true });
$(".comment_box").keypress(function() {
$(".commentButton").prop({ disabled: !$(this).val().length >= 1 })
});
关于javascript - 是否可以对 JQuery 中文本区域中输入的文本进行实时检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161995/