HTML に属性があることは知っていますが、文字ではなく入力する単語maxlength
の数を制限したいと考えています。
10 単語の後、ユーザーはカーソルを左に移動してテキストを編集できますが、それ以上単語を追加することはできません。
では、どうすればカーソルを停止できますか?
助言がありますか?
JavaScriptのみでお願いします。
HTML に属性があることは知っていますが、文字ではなく入力する単語maxlength
の数を制限したいと考えています。
10 単語の後、ユーザーはカーソルを左に移動してテキストを編集できますが、それ以上単語を追加することはできません。
では、どうすればカーソルを停止できますか?
助言がありますか?
JavaScriptのみでお願いします。
@sgrovesのように、この答えはただの楽しみです:)
$(document).ready(function(){
$('textarea').on('keydown', function(e){
// ignore backspaces
if(e.keyCode == 8)
return;
var that = $(this);
// we only need to check total words on spacebar (i.e the end of a word)
if(e.keyCode == 32){
setTimeout(function(){ // timeout so we get textarea value on keydown
var string = that.val();
// remove multiple spaces and trailing space
string = string.replace(/ +(?= )| $/g,'');
var words = string.split(' ');
if(words.length == 10){
that.val(words.join(' '));
}
}, 1);
}
});
});