Insert a variable from JS to Django form input field

django, html, javascript, python

Solution

If you're using plain javascript (not jQuery or any frameworks) you can access the field by `document.getElementById('id_distance').value`. You can set it's value by `document.getElementById('id_distance').value = <some_var>;`

Problem

I am writing a form that pays an employee's mileage between two cities. I am using the Google Maps API to get the information. I am running a script that yields a variable `drivingDistanceMiles`. I would like to populate the field in my Django form `mileage`, which saves to a python variable `distance`. Here is a snippet of my form html: ``` <form action="" method="post"><% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.distance.errors }} <label for="id_distance">Mileage claim:</label> {{ form.distance }} </div> ``` There is a distance calculator on the page just above the entry. In my forms.py `distance = forms.CharField(max_length=20, required = False)`. I made this a CharField instead of an IntField in case my employees (not the most computer savvy bunch) add the word 'miles' at the end. THE QUESTION: Is it possible to get the value of `drivingDistanceMiles` to auto-populate when the user enters their city info into the distance calculator?

Original source