2017-11-05 20 views
0

私はこのボックスを8ワードに制限しようとしていますが、スペースを "カンマスペース"に置き換えても 誰かがこれをどうすればいいのかアドバイスできますか?スペースは作業を置き換えますが、両方を置き換えません。同じ入力ボックスの2つのJquery

はここ

は私のHTMLは

<input name="input_4" type="text" id="input_10_4" size="100" /> 

で、ここに私のjQueryのここ

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"); 
    } 
    }); 
}); 

答えて

0

ですありがとう、私はこれを行うだろうかです。あなたが望むのとまったく同じではありませんが、IMHOはより良いユーザーエクスペリエンスです。

// 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>

関連する問題