Issue
I am trying to make an RPG character-sheet using flask. In this project I have two buttons ( level+ and level- ) that add or decrease the level of the character when pressed on.
So I have my html file:
<div class="level">
<button type="button" name="level-">-</button>
<p>{{ level }}</p>
<button type="button" name="level+">+</button>
</div>
and my flask file:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def index():
level = 0
return render_template('index.html', level=level)
if __name__ == '__main__':
app.run(debug=True)
How do I access the buttons such that I can increment or decrement the level variable in the python file?
Solution
I suggest doing this with javascript instead since it's less resource-intensive than sending a request to the backend and passing the new level to the template.
<div class="level">
<button type="button" name="level-" onclick="changeLevel(-1)">-</button>
<p id="level_number">{{ level }}</p>
<button type="button" name="level+" onclick="changeLevel(1)">+</button>
</div>
<script>
function changeLevel(change) {
var x = document.getElementById("level_number");
if (parseInt(x.innerHTML) + change >=0){
x.innerHTML = parseInt(x.innerHTML) + change;
}
}
</script>
If you need the level in your backend, then you could use AJAX or use a hidden input in a form and read the value in the backend using request.form["level_number"]
<form class="level">
<button type="submit" name="level-" onclick="changeLevel(-1)">-</button>
<p id="level_number">2</p>
<input type="hidden" name="level_number" id="hidden_level_number" value="{{ level }}"/>
<button type="submit" name="level+" onclick="changeLevel(1)">+</button>
</form>
<script>
function changeLevel(change) {
var x = document.getElementById("level_number");
var y = document.getElementById("hidden_level_number");
if (parseInt(x.innerHTML) + change >=0){
x.innerHTML = parseInt(x.innerHTML) + change;
y.value=x.innerHTML;
}
}
</script>
Answered By - Jaymit
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.