下面小编就为大家带来一篇JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
js判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)
文本输入时,由于数据库表字段长度限制会导致提交失败,因此想到了此方法验证。
废话不多说上代码:
<html> <head> <title>js判断输入字符串长度(汉字算两个字符,字母数字算一个)</title> <style type="text/css"> .pbt { margin-bottom: 10px; } .ie6 .pbt .ftid a, .ie7 .pbt .ftid a { margin-top: 1px; } .cl:after { clear: both; content: "."; display: block; height: 0; visibility: hidden; } </style> <script type="text/javascript"> //获取字符串长度(汉字算两个字符,字母数字算一个) function getByteLen(val) { var len = 0; for (var i = 0; i < val.length; i++) { var a = val.charAt(i); if (a.match(/[^\x00-\xff]/ig) != null) { len += 2; } else { len += 1; } } return len; } // 只要键盘一抬起就验证编辑框中的文字长度,最大字符长度可以根据需要设定 function checkLength(obj) { var maxChars = 80;//最多字符数 var curr = maxChars - getByteLen(obj.value); if (curr > 0) { document.getElementById("checklen").innerHTML = curr.toString(); } else { document.getElementById("checklen").innerHTML = '0'; document.getElementById("subject").readOnly = true; } } </script> </head> <body> <p class="pbt cl"> <textarea id="subject" maxlength="80" onkeyup="checkLength(this)" accesskey="1" tabindex="11"></textarea> <span id="subjectchk">还可输入 <strong id="checklen" style="color: #FF0000">80</strong> 个字符 </span> <span id="postNameRule" class="spn_flag_1" style="display: none"></span> </p> </body> </html>
以上这篇JS判断输入字符串长度实例代码(汉字算两个字符,字母数字算一个)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version