javascript - Javascript 如何在 Textarea 表单字段中获取准确的字符数
问题描述
我一直在谷歌和线程中搜索如何解决这个问题,但没有找到我需要的东西。我正在使用 JS 对表单中的 textarea 字段进行一些字符倒计时。在我尝试使用提交的数据之前,我的做法非常标准并且有效。
我的代码:
$(document).ready(function(){
$('#available_days_times').keyup( function(){
showLength( $('#available_days_times'), $('#available_days_times_label'), 1000 );
});
...
});
function showLength(field_id, label_id, maxLength){
var currentLength = field_id.val().length;
var charactersLeft = maxLength - currentLength;
label_id.addClass("red");
if( currentLength >= maxLength ) {
charactersLeft = 0;
field_id.val( field_id.val().substring(0, maxLength-1) )
}
label_id.text("Characters allowed: " + maxLength + " You have " + charactersLeft + " characters left");
}
这工作正常,直到我复制粘贴超过 1000 个字符的文本(如下)。代码将其截断为 1000 个字符,但在将表单数据提交到数据库表时出现大小错误。maxLength 等于该字段的 db table.column 的大小。
这是我用于测试的文本示例:
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
monday = 8:00am to 4:00pm
wednesday = 8:00am to 5:00pm
friday = 12:00pm to 5:00pm
saturday = 5:00pm to 9:00pm
sunday = n/a
mond
如果我将其复制粘贴到表单的 textarea 中,javascript 将其视为 999 个字符,但我的数据库将其视为 1038 并抛出一个合适的字符。
由于没有真正奇怪的字符,我认为 javascript 没有将返回数计为两个字符。大约有 40 行,大约匹配 999 和 1038 之间的差异。
有没有办法,使用 JavaScript 来获得与 db 看到的计数相匹配的字符的准确计数?
谢谢你的帮助。
解决方案
推荐阅读
- python - yFinance 多股票代码信息不起作用
- python - pdf2image python 上传pdf文档
- python - 如何使用特殊字母对空格字符进行排序?
- xapi - 如何在xapi中存储带有时间戳的时区?
- excel - 复制粘贴范围不复制范围内的所有值
- linux - 内核 linux-ti-staging-5.10 上带有 Yocto-Linux (dunfell) 的 BBB 上没有可用的 /dev/uio* 设备
- npm - NPM 和 CI:--cache 与 node_modules/
- java - 在 Eclipse 中禁用“下载源代码和 javadoc”
- regex - 正则表达式:匹配引用文本中的模式
- python - How to access JSON elements in python swiftly and efficiently?