I’m developing a word counter web application using HTML, JavaScript, and Flask. The issue I’m encountering is that the form submits on every keystroke, which is not what I want. I need the form to update the word count dynamically without submitting on each keystroke. Below is my current code:
Python Script -
from flask import Flask, render_template, url_for, request
app = Flask(__name__)
@app.route("/", methods =["GET", "POST"])
def home():
user_input = request.form.get("user_input")
if user_input:
print(user_input)
return render_template("index.html")
""" Step 1 - User types or paste in text
Step 2 - As soon as someone types in the function
in python starts """
if __name__ == '__main__':
app.run(debug=True)
HTML -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Counter</title>
<style>
* {
margin: auto;
padding: 0;
}
textarea, label{
display: flex;
justify-content: center;
align-items: center;
}
#user_input{
width: 600px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<div>
<div class="div1">
<form id="input_form" action="/" method="POST">
<label for="user_input">Type or paste your text below 👇</label>
<textarea name="user_input" id="user_input"></textarea>
</form>
</div>
<div class="div-2">
<p>Words: <span id="word_count">0</span></p>
</div>
</div>
<script>
const user_inp = document.getElementById("user_input");
const form_input = document.getElementById("input_form");
user_inp.addEventListener("input", function() {
form_input.submit();
});
</script>
</body>
</html>
I don't know how to get past this.