count characters textarea and change color counted

。_饼干妹妹 提交于 2021-01-28 06:44:28

问题


I have the simple code, it's works fine. This code counting characters in textarea and result show in div 0,1,2 etc. I would like obtain effect when result counted is < 100 font-color will be red and when counted result is > 100 change font-color on green. How can i do it?

function countChar1(val) {
  var len = val.value.length;

  $('#charNum').text(0 + len);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<textarea id="opis_siebie" type="text" rows="6" cols="15" name="opis_siebie" onkeyup="countChar1(this)"></textarea><br />

<div id="charNum" ">0</div>

回答1:


you already have the length of the text, add an if statement and change the color accordingly

function countChar1(val) {
  var len = val.value.length;
  var color;
  $('#charNum').text(0 + len);

  color = len < 100 ? 'red' : 'green';
  $('#charNum').css({
    'color': color
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<textarea id="opis_siebie" type="text" rows="6" cols="15" name="opis_siebie" onkeyup="countChar1(this)"></textarea><br />
<div id="charNum" ">0</div>


来源:https://stackoverflow.com/questions/49969868/count-characters-textarea-and-change-color-counted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!