1

I have the following models.py file which has the table and modelform. I'm working with has and the HTML template and I want some JavaScript code to multiply the value of rate input and quantity input then set it dynamically into total cost input before I click on submit.

ModelForm:
class ExpenseBasedTransactionForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ExpenseBasedTransactionForm, self).__init__(*args, **kwargs)
        eb_client = Clientele.objects.filter(clientele_type__icontains='eb client').values_list("id", "clientele_name")
        eb_main = []
        for i in eb_client:
            k = list(i)
            k[0] = str(k[0])
            l = (tuple(k))
            eb_main.append(l)
        self.fields['eb_client'] = ChoiceField(choices=eb_main, label='EB Client', )

    class Meta:
        model = ExpenseBasedTransaction
        # fields = '__all__' #to include all the fields in the form

        # specify what fields to be included in the form
        fields = ['date_initiated', 'eb_client', 'rate',
                  'quantity', 'total_cost']

        widgets = {
            'date_initiated': AdminDateWidget(),
            'rate': NumberInput(attrs={'class': 'form-control', 'id': 'rate'}),
            'quantity': NumberInput(attrs={'class': 'form-control', 'id': 'quantity'}),
            'total_cost': NumberInput(attrs={'class': 'form-control', 'id': 'total'}),
        }


html:

{% extends "base.html" %}
{% load bootstrap3%}
{% block content %}
    <div class="content-wrapper" id="tab">
        <div class="content">
            <div class="head">
                <div class="row">               
                    <div class="col-sm-7 title" >
                        <span><i class="fa fa-pencil"></i> Record An Expense</span>
                    </div>
                    </div>
                </div>
            <div class="content padding table-responsive" >
                <div class="wrapper">
                    <form method="post">
                    {% csrf_token %}
                    {% bootstrap_form form %}
                    <br>
                    <button type="reset" class="btn btn-warning m-sm-right"><i class="fa fa-trash-o fa-lg 
                     white" aria-hidden="true"></i> Clear</button>
                    <button id="proceed" class="btn btn-primary m-sm-right">Proceed <i class="fa fa- 
                     arrow-circle-right fa-lg white" aria-hidden="true"></i></button>
                    </form>
                </div>
            </div>
        </div> <!-- end of content -->
    </div> <!--end of content-wrapper -->
<script type="text/javascript">

</script>
{% endblock content %}
2
  • 1
    Welcome! Are you sure that it is a good idea to calculate total_cost on the client side? I think the better choice is to do it when you are saving your form in your view (server side). Commented May 26, 2020 at 21:19
  • yes, the user will be an authorized user... thanks for the response. i still need help Commented May 26, 2020 at 22:26

1 Answer 1

1

please try this:

update your widgets in Modelform (note that you needn't set custom id in your modelform widget, just add onchange event:

widgets = {
        'date_initiated': AdminDateWidget(),
        'rate': NumberInput(attrs={'class': 'form-control', 'onchange': 'calculateTotalCost()'}),
        'quantity': NumberInput(attrs={'class': 'form-control', 'onchange': 'calculateTotalCost()'}),
        'total_cost': NumberInput(attrs={'class': 'form-control'}),
    }

and then describe this event-function in your template (add this code to your template between script tag:

function calculateTotalCost () {
    var rate = Number(document.getElementById('id_rate').value);
    var quantity  = Number(document.getElementById('id_quantity').value);
    if (rate && quantity) { 
        document.getElementById('id_total_cost').value = rate * quantity
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the response once again but unfortunately this did not work with my code
yes boss. the error on the console says; Uncaught ReferenceError: calculateTotalCost is not defined at HTMLInputElement.onchange ((index):142)
update your template please with that javascript code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.