Приведенный ниже код работает в соответствии с запросом, я добавил некоторые атрибуты к текстовым областям, чтобы вы могли иметь несколько текстовых областей на одной странице, все с разными ограничениями.
Вам необходимо добавить следующееатрибуты word-limit="true"
, max-words='n'
, min-words='n'
.Заполнитель больше не нужен, потому что код автоматически генерирует один за другим загрузку страницы.
Это немного сложнее, чем ваш пример, но позволяет вам делать больше (не уверен, каков ваш общий проект).
Количество слов
Основной код для подсчета слов выглядит следующим образом:
wordCount = $.trim( $("#writing").val() ).split(/\s+/).filter(Boolean).length;
Объяснение кода:
$("#writing").val()
- получает значение текстовой области (то есть строки) .trim()
удаляет все пробелы в начале или конце строки .split(/\s+/)
делитстрока вокруг каждого пробела и помещает их в массивт.е. сколько слов существует)
Демо
// Cycle through each textarea and add placeholder with individual word limits
$("textarea[word-limit=true]").each(function() {
$(this).attr("placeholder", "Writing entries: " + $(this).attr("min-words") + " words min, " + $(this).attr("max-words") + " words max");
});
// Add event trigger for change to textareas with limit
$(document).on("input", "textarea[word-limit=true]", function() {
// Get individual limits
thisMin = parseInt($(this).attr("min-words"));
thisMax = parseInt($(this).attr("max-words"));
// Create array of words, skipping the blanks
var removedBlanks = [];
removedBlanks = $(this).val().split(/\s+/).filter(Boolean);
// Get word count
var wordCount = removedBlanks.length;
// Remove extra words from string if over word limit
if (wordCount > thisMax) {
// Trim string, use slice to get the first 'n' values
var trimmed = removedBlanks.slice(0, thisMax ).join(" ");
// Add space to ensure further typing attempts to add a new word (rather than adding to penultimate word)
$(this).val(trimmed + " ");
}
// Compare word count to limits and print message as appropriate
if ( wordCount < thisMin) {
$(this).parent().children(".writing_error").text("Word count under " + thisMin + ".");
} else if (wordCount > thisMax) {
$(this).parent().children(".writing_error").text("Word count over " + thisMax + ".");
} else {
// No issues, remove warning message
$(this).parent().children(".writing_error").text("");
}
});
.writing_error {
color: red;
}
[id^=writing] {
border-bottom: 1px solid grey;
margin-bottom: 20px;
padding-bottom: 20px;
}
label {
width: 100%;
}
textarea {
width: 100%;
margin-top: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=writing1 class=cond>
<label class="required">Writing Entry 1</label>
<textarea name=writ word-limit="true" max-words="600" min-words="100"></textarea>
<span></span>
<div class="writing_error"></div>
</div>
<div id=writing2 class=cond>
<label class="required">Writing Entry 2</label>
<textarea name=writ></textarea>
<span></span>
<div class="writing_error"></div>
</div>
<div id=writing3 class=cond>
<label class="required">Writing Entry 3</label>
<textarea name=writ word-limit="true" max-words="10" min-words="4"></textarea>
<span></span>
<div class="writing_error"></div>
</div>