简体   繁体   English

计数在textarea写的词

[英]Count word written in textarea

I am trying to count the number of times a keyword from input field is used throughout a text that user have written in a textarea. 我试图计算在用户在textarea中编写的文本中使用输入字段中的关键字的次数。 I kinda made it work but having some issues. 我有点工作,但有一些问题。 How can I make the search do live search instead of as it is now, where user have to push a button in order for the code to search? 我如何使搜索进行实时搜索而不是现在,用户必须按下按钮才能搜索代码?

$(function() {
  function numHits(n, h) {
    var c, re = new RegExp(n, "g");
    c = (h.match(re) || []).length;
    return c;
  }
  $("#finder").submit(function(e) {
    e.preventDefault();
    $("#keyword-count").html(numHits($("#keyword-input").val(), $("#my-txt-area").val()));
  });
});
<form id="finder">
  <textarea name="mytxtarea" id="my-txt-area" cols="100" rows="10"></textarea>
  <br>
  <div class="input-area" id="div-keywords">
    <input type="text" id="keyword-input" placeholder="Enter keyword..." /> <button id="search-keyword" type="submit">Search</button>
  </div>
</form>
<p>Your word has been used <span id="keyword-count">0</span> times throughout the text.</p>

Code Snippet 代码片段

You just have to place the function on keyup event of your query box 您只需将该函数放在查询框的keyup事件上即可

$(function() {
  function numHits(n, h) {
    var c, re = new RegExp(n, "g");
    c = (h.match(re) || []).length;
    return c;
  }
  $("#keyword-input").keyup(function(e) {
    e.preventDefault();
    $("#keyword-count").html(numHits($("#keyword-input").val(), $("#my-txt-area").val()));
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM