Reputation: 11098
I have a "post" button that activates (goes from blurred to colour and from disabled to enabled) when text is typed into the text area.
This works fine but I would like the text area to detect when there is nothing in the text area. So let's say I typed "abc" into the text area.. the submit button would become active but let's say I now delete all the text.. The button is still active.. well not fully as I have this:
commentButton.prop({ disabled: commentBox.val() == 0 });
Which stops the form from submitting with nothing in the textarea. The issue is the submit button is still in colour and doesn't return back to it's blurred inactive state as expected.
So this brings me to my question..
Can I set up something that will activate and start listening as soon as i focus in the text area and type and know when I've deleted everything from the text area?
This way I can set up an if statement to say if text is all deleted then removeClass for coloured state button and addClass for blurred state button.
Also this should apply to white spaces also.
Here is my current code:
.comment_box = my text area
.activeCommentButton = coloured submit button
.commentButton = blurred submit button
$(".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("");
});
});
Kind regards
Upvotes: 0
Views: 180
Reputation: 11098
This worked for me but is there a cleaner way?
commentButton.prop({ disabled: true });
commentBox.off().on("keyup keypress input change", function () {
commentButton.prop({ disabled: commentBox.val().length == 0 });
if ( commentBox.val().length > 1 ) {
commentButton.removeClass("commentButton").addClass("activeCommentButton");
} else {
commentButton.removeClass("activeCommentButton").addClass("commentButton");
}
});
Upvotes: 0
Reputation: 144659
yes try this, you can modify it:
$(".commentButton").prop({ disabled: true });
$(".comment_box").keypress(function() {
$(".commentButton").prop({ disabled: !$(this).val().length >= 1 })
});
Upvotes: 3