两个Jquery用于相同的输入框

时间:2017-11-05 23:25:58

标签: jquery text replace count

我试图将该框限制为8个单词,但也用“逗号空间”替换Space 有人可以建议我如何做到这一点,我可以让单词计数工作或空间替换工作,但不是两者。

谢谢

这是我的HTML

jQuery("#input_10_4").keyup(function() {
  var textValue = $(this).val();
  textValue = textValue.replace(/ /g, ", ");
  $(this).val(textValue);
});
jQuery(document).ready(function() {

  $("#input_10_4").keyup(function() {

    var content = $("#input_10_4").val(); //content is now the value of the text box
    var words = content.split(/\s+/); //words is an array of words, split by space
    var num_words = words.length; //num_words is the number of words in the array
    var max_limit = 8;
    if (num_words > max_limit) {
      alert("Exceeding the max limit");
      var lastIndex = content.lastIndexOf(" ");
      $("#input_10_4").val(content.substring(0, lastIndex));

      $('#remainingChars').text('Limit Exceeding');
      return false;
    } else {
      $('#remainingChars').text(max_limit + 1 - num_words + " words remaining");
    }
  });
});

这是我的Jquery

    for tcp_obj in data[0]:
        print("checking" + str(tcp_obj.RemoteIpAddress))
        os.system("isthisipbad.py --ip " + str(tcp_obj.RemoteIpAddress))

1 个答案:

答案 0 :(得分:0)

我将如何做到这一点。它并不完全像你想要的那样,但恕我直言,它是一个更好的用户体验。



// this timer function allows us to wait till the user is done typing,
//  rather than calling our code on every keypress which can be quite annoying
var keyupDelay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();  

$('#input_10_4').keyup(function() {
    var $this = $(this);
    // use our timer function
    keyupDelay(function(){
       // user has stopped typing, now we can do stuff 
       var max_limit = 8;
       var words = $this.val().trim().replace(/,/g, ' ').replace(/,?\s+/g, ' ').trim().split(' ');
       
       words = words.slice(0, max_limit); // get all the words up to our limit
       console.log(words);
       var wordString = words.join(', '); 
       $this.val(wordString);
       var remainingWords = max_limit - words.length;
       $('#remainingChars').text('Words remaining: '+remainingWords); 
    }, 800 ); // number of milliseconds after typing stops, this is equal to .8 seconds
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <input name="input_4" type="text" id="input_10_4" size="100" />
 <br>
 <div id="remainingChars"></div>
&#13;
&#13;
&#13;