Satish Kumar
Satish Kumar

Reputation: 131

Flask-wtforms: Multiply two numbers from two different input fields and populate the result in third input field without refreshing the page

I'm working on a feature where if I input values to two different input fields then I should multiply and show into third input box without refreshing the page.

Example:-

enter image description here

Code:- forms.py

class Multiply(FlaskForm):
    number1 = IntegerField("number1")
    number2 = IntegerField("number2")
    result = IntegerField("result")

routes.py

@app.route('/multiply')
def multiply():
    form = Multiply()
    return render_template('multiply.html', form=form)

multiply.html

<form>
    {{ form.number1.label }} {{ form.number1(class="form-control") }}
    {{ form.number2.label }} {{ form.number2(class="form-control") }}
    {{ form.result.label }} {{ form.result(class="form-control") }}
</form>

I'm new to this so I don't know how to do this.

Upvotes: 0

Views: 1459

Answers (2)

ybl
ybl

Reputation: 1615

What you are trying to do is to update your view dynamically. HTML needs the help of javascript to dynamically update the page(in your case the result).

This can be done using an AJAX call to an API written on your backend which receives your two values as data and calculates the result and sends it back(possibly also storing it at the same time).

More info

Upvotes: 1

Till
Till

Reputation: 323

You will find that this exact example is described in the Flask documentation. See the AJAX with jQuery example here.

The JSON view function:

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/_add_numbers')
def add_numbers():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    return jsonify(result=a + b)

@app.route('/')
def index():
    return render_template('index.html')

Html template:

<script type=text/javascript>
 $(function() {
  $('a#calculate').bind('click', function() {
   $.getJSON($SCRIPT_ROOT + '/_add_numbers', {
    a: $('input[name="a"]').val(),
    b: $('input[name="b"]').val()
   }, function(data) {
    $("#result").text(data.result);
   });
   return false;
  });
 });
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
 <input type=text size=5 name=b> =
 <span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>

Upvotes: 1

Related Questions