从JS插入一个变量到Django表单输入字段 [英] Insert a variable from JS to Django form input field

查看:258
本文介绍了从JS插入一个变量到Django表单输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写一份支付两个城市之间员工里程的表格。我正在使用Google Maps API来获取信息。我正在运行一个产生变量 drivingDistanceMiles 的脚本。我想在我的Django窗体里程中填充这个字段,它保存到一个python变量 distance 中。

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.

以下是我的表单html代码片段:

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.

在我的forms.py distance = forms.CharField(max_length = 20,required = False)中。如果我的员工(不是最精通计算机的人)在最后添加miles这个词,我将其设置为CharField而不是IntField。

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.

问题:当用户进入城市时,是否可以获取 drivingDistanceMiles 的值来自动填充信息到距离计算器?

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?

推荐答案

如果您使用的是纯javascript(而不是jQuery或任何框架),您可以访问该字段由 document.getElementById('id_distance')。value 。您可以通过 document.getElementById('id_distance')。value =< some_var>;

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>;

这篇关于从JS插入一个变量到Django表单输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆