LoginSignup
0
0

More than 1 year has passed since last update.

jQueryで文字数チェッカーを作成してみた

Posted at

css

style.css
.input {
    position: relative;
    display: block;
    padding: 20px;
    width: 100%;
    background-color: #eee;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
.lest-count {
    position: absolute;
    bottom: 5px;
    right: 5px;
    font-family: Helvetica;
}
.red {
    color: red;
}

html,jquery

index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title></title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<input type="text" class="input" value="">
<span class="lest-count">30</span>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
// .input に文字を入力し、文字を入力した段階でその文字数に応じて .lest-count の値が減っていき、
// 最大文字数である30文字以上入力すると .lest-count に .red クラスが追加されて文字色が赤くなり、
// 30文字以内になると、.red クラスが外れ、文字色が元に戻る。(ちなみに改行は文字数に含まない。)

// keyup 文字入力後に発火されるイベント。
// .replace(/\s+/g,'').length 改行を含まない文字数を取得します。
// .val() input要素のvalueを取得します。
$(function(){
  var lc = $(".lest-count");
  $(".input").keyup(function(){ //文字が入力されたらイベントスタート
    var num = $(this).val().replace(/\s+/g,'').length;//val()でインプットの値を取得し、
    //replace(/\s+/g,'').lengthで改行とスペースを含めない文字数を取得
    lc.text(30-num);//inputの文字数文.lest-countの文字を減らす
    if(num > 30){
      lc.addClass("red");//numが30より上なら文字を赤くする
    }else if(num <= 30){
      lc.removeClass("red");//numが30以下なら文字を黒に戻す
    }
  });
});
</script>
</body>
</html>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0