I have a text area in a form that has a character limit and I want to disable the submit button if the character limit is exceeded or if there are no characters entered. When the user enters some characters but then proceeds to remove all of them again, leaving the text area empty, the send button remains enabled despite the check that's in place. Everything else works as I expect it to. It must be something simple but I just can't see it...
HTML:
<textarea name="t" id="message-input-field" autofocus="autofocus" placeholder=""></textarea>
<input type="submit" value="Send" id="send-message-button" class="button"/>
<span id="counter"></span>
jQuery:
// Disable by default
$('#send-message-button').prop('disabled', true);
// Do stuff when there is textarea activity
$('#message-input-field').on("propertychange input textInput", function () {
var charLimit = 140;
var remaining = charLimit - $(this).val().length;
if(remaining == charLimit) {
console.log("disabling");
// No characters entered so disable the button
$('#send-message-button').attr('disabled', true);
} if (remaining < 0) {
// remaining = 0; // Prevents the counter going into negative numbers
$('#counter').addClass("over-char-limit").text(remaining);
$('#send-message-button').attr('disabled', true);
} else {
$('#send-message-button').removeAttr('disabled');
$('#counter').removeClass("over-char-limit").text(remaining);
}
});
CSS
.over-char-limit {
color: red;
}
UPDATE:
I've settled on the following code which works fine for me now. It perhaps isn't the most efficient/elegant way to do it but to my simple mind it is quite clear and readable. Thanks to @Tats_innit and @gdoron for helping with the solution.
// Disable the send button by default. Enable only when text entered.
$('#send-message-button').prop('disabled', true);
// Character counter logic on the 'send message' text area. Rules are:
// 1. Counter appears on any input of text (pasting or key strokes).
// 2. Counter can go into negative numbers but changes to red when it does.
// 3. 'Send' button disabled when limit exceeded or no characters entered.
$('#message-input-field').on("propertychange input textInput", function() {
var charLimit = 140;
// Calculate how many characters remain (this could be a negative number)
var remaining = charLimit - $(this).val().length;
// Add the counter value to #counter
$('#counter').text(remaining);
if (remaining == charLimit) {
// Disable the button as no characters entered
$('#send-message-button').prop('disabled', true);
$('#counter').removeClass("over-char-limit");
} else if (remaining < 0) {
// Disable the button as too many characters entered
// remaining = 0; // Prevents the counter going into negative numbers
$('#send-message-button').prop('disabled', true);
$('#counter').addClass("over-char-limit");
} else {
// Happy case: characters have been entered but do not exceed limit
$('#send-message-button').prop('disabled', false);
$('#counter').removeClass("over-char-limit");
}
});