我在一个有字符限制的表单中有一个文本区域,如果超出字符限制或没有输入字符,我想禁用提交按钮。当用户输入了一些字符但随后又继续删除所有字符时,文本区域为空,尽管检查已到位,但发送按钮仍保持启用状态。其他一切都按我的预期工作。它一定很简单,但我就是看不到它......
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;
}
更新:
我已经确定了以下代码,它现在对我来说很好。这可能不是最有效/最优雅的方式,但在我看来,它非常清晰易读。感谢 @Tats_innit 和 @gdoron 帮助解决问题。
// 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");
}
});