Home > Web Front-end > JS Tutorial > How does js determine the length of the input string_javascript skills

How does js determine the length of the input string_javascript skills

WBOY
Release: 2016-05-16 15:25:24
Original
2047 people have browsed it

JS determines the length of the input string (Chinese characters count as two characters, letters and numbers count as one)

When text is entered, the submission fails due to the length limit of the database table field, so this verification method was thought of.

Without further ado, let’s talk about the code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

<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>

  <div 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>

  </div>

</body>

</html>

Copy after login

The above is how js determines the length of the input string. I hope it will be helpful to everyone's learning and learn how to determine the length of the input string.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template