jQuery 字符计数 onkeyup 显示 1 个字符,当 0 离开时
jQuery character count onkeyup showing 1 character when 0 left
我正在使用 jQuery 来显示文本输入中剩余的字符,它工作正常,但是当它达到 0 个剩余字符时,它显示 1 个,即使它不允许您输入更多字符。这可能是一件显而易见且简单的事情,但今天却让我很困惑。这是我正在使用的代码:
= form.text_field :name, { required: true, class: "#{'error' if @project.errors[:name].present?}", placeholder: '40 characters max', maxlength: 40, :onkeyup => "countCharname(this)" }
span id="charName" class="margin-left-5"
function countCharname(val) {
var len = val.value.length;
if (len >= 40) {
val.value = val.value.substring(0, 40);
} else {
$('#charName').text(40 - len);
}
};
未经测试,我的假设是当它达到最大长度时,输入长度为 40。这意味着 if 语句 (len >= 40)
为真,因此更新 $('#charName')
与剩余的字符,没有得到 运行.
尝试将 if 语句更改为 (len > 40)
我正在使用 jQuery 来显示文本输入中剩余的字符,它工作正常,但是当它达到 0 个剩余字符时,它显示 1 个,即使它不允许您输入更多字符。这可能是一件显而易见且简单的事情,但今天却让我很困惑。这是我正在使用的代码:
= form.text_field :name, { required: true, class: "#{'error' if @project.errors[:name].present?}", placeholder: '40 characters max', maxlength: 40, :onkeyup => "countCharname(this)" }
span id="charName" class="margin-left-5"
function countCharname(val) {
var len = val.value.length;
if (len >= 40) {
val.value = val.value.substring(0, 40);
} else {
$('#charName').text(40 - len);
}
};
未经测试,我的假设是当它达到最大长度时,输入长度为 40。这意味着 if 语句 (len >= 40)
为真,因此更新 $('#charName')
与剩余的字符,没有得到 运行.
尝试将 if 语句更改为 (len > 40)