Warm tip: This article is reproduced from stackoverflow.com, please click
django django-forms django-templates javascript jquery

How to autofill form box value filling other one?

发布于 2020-11-15 03:55:55

I have created a form in django using this class model:

#models.py

    class Example(models.Model):
        var_a=models.DecimalField()
        var_b=models.DecimalField()
        var_c=models.DecimalField()

Suppose that I have created a form using this variable:

#template.html

    <form id="example" method="post">
      <div class="form-group col-2 0 mb-0" id="var_a" >
         {{form.var_a|as_crispy_field}}
      </div>
     <div class="form-group col-2 0 mb-0" id="var_b" >
         {{form.var_b|as_crispy_field}}
     </div>
     <div class="form-group col-2 0 mb-0" id="var_c" >
         {{form.var_c|as_crispy_field}}
     </div>

Now I want to create a jQuery code that give me the possibility to autofill var_c when I insert value in the form box of var_a and var_b.

In particular I want to figure out the following equation:

var_c=var_a*var_b

Is it possibile to get it?

Edit

I have tried to use the following code:

$(document).ready(function () {
          $('#var_a, #var_b').change(function (){
            var a = $('#var_a').val();
            var b = $('#var_b').val();
            $('#var_c').val(a*b);
          })
        });

But does not works. If I fill the box of form of var_a and var_b does not appear nothing in the var_c box form

Questioner
Federico De Marco
Viewed
5
Pruthvi Barot 2020-07-09 16:22
$(document).ready(function () {
  $('#id_var_a, #id_var_b').change(function (){
    var a = $('#id_var_a').val();
    var b = $('#id_var_b').val();
    $('#id_var_b').val(a*b);
  })
});