我想给TextAreaField添加一个实时的字数统计功能,并且已经确定可以使用jQuery来完成。我的代码基于下面的例子:
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.5.0.js">
</script>
</head>
<body>
<h1>Example Word Count</h1>
<input type="text" id="word-count" />
<input type="text" id="feedback" disabled />
<script>
function wordCount(field) {
var number = 0;
// Split the value of input by
// space to count the words
var matches = $(field).val().split(" ");
// Count number of words
number = matches.filter(function (word) {
return word.length > 0;
}).length;
// Final number of words
$("#feedback").val(number);
}
$(function () {
$("input[type='text']:not(:disabled)")
.each(function () {
var input = "#" + this.id;
// Count words when keyboard
// key is released
$(this).keyup(function () {
wordCount(input);
});
});
});
</script>
</body>
</html>
作为jQuery的新手,我不确定如何合并我的Flask-WTF表单,以便在表单中键入的单词在旁边的框中进行计数。
以下是我的form.py的摘录:
class DeclineForm(FlaskForm):
feedback = TextAreaField("",validators=[DataRequired(), Length(min=15)], render_kw={"placeholder": "Don't forget to include at least 15 words"})
submit = SubmitField("Decline")下面是我当前表单HTML代码:
<button class="btn btn-primary btn-sm" data-toggle="collapse" href="#collapse-decline-{{ submission.id }}" aria-expanded="false" aria-controls="collapseExample">Decline</button>
<form action="" method="POST">
<div class="collapse" id="collapse-decline-{{ submission.id }}">
<div class="form-group">
{{ decline_form.feedback.label(class="form-control-label") }}
{% if decline_form.feedback.errors %}
{{ decline_form.feedback(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in decline_form.feedback.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
<input type="text" id="word-count" disabled/>
{{ decline_form.feedback(class="form-control form-control-lg") }}
{% endif %}
</div>
<script>
function wordCount(field) {
var number = 0;
var matches = $(field).val().split(" ");
number = matches.filter(function (word) {
return word.length > 0;
}).length;
$("#word-count").val(number);
}
$(function () {
$("input[type='text']:not(:disabled)")
.each(function () {
var input = "#" + this.id;
$(this).keyup(function () {
wordCount(input);
});
});
});
</script>
<input type="hidden" name="submission-id" value="{{submission.id}}"></input>
<input type="submit" class="btn btn-primary btn-sm" name="review-submission" value="Decline">
</input>
</div>
</form>如何更新jQuery代码以实现Flask-WTF表单{{ decline_form.feedback(class="form-control form-control-lg") }}
发布于 2021-09-10 07:47:18
您需要更改jQuery选择器$("input[type='text']:not(:disabled)")以匹配您的textarea,因为您不使用<input>。
$("textarea")此外,您还需要为textarea字段提供一个id,我不确定WTForms如何处理id属性。它可能是自动的,只要确保在呈现的HTML中您的文本区域具有id属性即可。
如果没有,请检查文档:https://wtforms.readthedocs.io/en/2.3.x/fields/#the-field-base-class
https://stackoverflow.com/questions/69128472
复制相似问题