特殊的jQuery字符数

时间:2016-06-22 10:44:38

标签: javascript jquery countdown

我真的希望你能帮助我。我有一个简单的jQuery字符计数脚本,当用户将字符输入文本字段时,该脚本会倒计时。但是现在我需要以两种方式自定义它:

1。)我需要添加一个复选框。当此复选框为checked时,字符数必须按一定数量计算,例如10个字符。

2.。)字符数目前仅显示我开始输入第一个字符时,但是我想要在页面加载时显示字符数。

如果您有任何疑问,请告知我们。

您可以在下面找到我的代码:

function countChar(val) {
    var len = val.value.length;
    if (len >= 500)
        val.value = val.value.substring(0, 500);
    else 
        $('#charNum').text(500 - len);
};
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>

    //Sorry for making too many functions, well you also use other approches as well.

    var len;
    //for initiliase the count text value on page
      function init(){
    $("#charNum").text(500)
}

    //for keyup and checkbox
      function countChar() {
        len = $("#field").val().length;
        if (len >= 500) {
          val.value = val.value.substring(0, 500);
        }
        if($("#idk").is(":checked"))
        {
          $("#charNum").text(500-($("#field").val().length +10));
        }
         else {
          $('#charNum').text(500 - len);
        }
      }
    </script>
  </head>

  <body onload="init();">
    <textarea id="field" onkeyup="countChar()"></textarea>
    <input type="checkbox" name="chk" id="idk" onchange="countChar()" />
    <div id="charNum"></div>
  </body>

</html>

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
  <script>
    //Sorry for making too many functions, well you also use other approches as well.

    var len;
     //for initiliase the count text value on page
    function init() {
      $("#charNum").text(500)
    }

     //for keyup  
    function countChar() {
      len = $("#field").val().length;
      if (len >= 500) {
        val.value = val.value.substring(0, 500);
      }
      if ($("#idk").is(":checked")) {
        $("#charNum").text(500 - ($("#field").val().length + 10));
      } else {
        $('#charNum').text(500 - len);
      }
    }
  </script>
</head>

<body onload="init();">
  <textarea id="field" onkeyup="countChar()"></textarea>
  <input type="checkbox" name="chk" id="idk" onchange="countChar()" />
  <div id="charNum"></div>
</body>

</html>
&#13;
&#13;
&#13;

相关问题