JavaScript 文字数チェック

入力文字数をkeyupによるthis.value.lengthで取得し、条件分岐で、CSSの要素を変える処理を作ります。

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comment</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
        <div class="container">
            <textarea id="comment" placeholder="your comment here"></textarea>
            <div class="btn">Submimt</div>
            <p><span id="label"></span> characters left</p>
             
      <script src="myscript.js">
      </script>
  </body>
</html>

styles.css

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
@charset "utf-8";
 
body {
    font-family: Verdana, sans-serif;
    font-size: 16px;
    background: #e0e0e0;
}
 
.container {
    width: 400px;
    margin: 30px auto;
}
 
textarea {
    width: 400px;
    box-sizing: border-box;
    height: 200px;
    padding: 14px;
    font-size: 16px;
    border: none;
    border-radius: 5px;
    margin-bottom: 14px;
    line-height: 1.5;
}
textarea:focus {
    outline: none;
}
 
p {
    color: #333;
    font-size: 14px;
    margin: 0;
    padding-top:8px;
}
 
#label{
    font-weight: bold;
}
 
.btn {
    display: inline-block;
    width: 150px;
    background: #00aaff;
    padding: 5px;
    color: #fff;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    box-shadow: 0 4px 0 #0088cc;
    float: right;
}
 
.warning {
    color:red;
}

myscript.js

(function(){
		'use strict';

		var comment = document.getElementById('comment');
		var label = document.getElementById('label');

		var LIMIT = 20;
		var WARNING = 10;

		label.innerHTML = LIMIT;

		comment.addEventListener('keyup', function(){
				var remaining = LIMIT - this.value.length;
				label.innerHTML = remaining;
				if (remaining < WARNING){
					label.className = 'warning';
				} else {
					label.className = '';
				}
		});
})();

%e7%84%a1%e9%a1%8c