How to return a value from javascript function to django template in the same view?

I am just getting a value from an input tag by javascript. But Now I need to pass this value to the Django template on the same page to do my required task.

    <h1>In Django Template</h1>
    <input type="text" id="agency_id" name="fname" value="1">
    <select class="select" name="delivery_agent" id="DeliveryAgent">
    <option class="form-control" value="{{ }}" {% if == delivery_agency_id  %} selected="selected" {% endif %}>{{ }}
  </option> {% endfor %}

  var delivery_agency_id = document.getElementById("agency_id").value;
  alert(delivery_agency_id )

Here, I am getting the agency_id by script. Now I need to pass it to the if condition as above code. Please help me to solve it.

To assign a value from any template, in this case Django you would just interpolate it. Something like

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";

Ref: Django Template Variables and Javascript

If you just need to compare the value, you don't need to pass the value back to template. To do this purely in HTML and JS you can check this,js,output

Important parts are

<select name="" id="deliveryAgent" onChange="checkValue()">


function checkValue() {
  var sel = document.getElementById('deliveryAgent');
  var val = sel.value;
  if(val === "1") {
    alert("found 1")

BTW if you need to have this part if(val === "1") { dynamically set, then in the template engine you set this value.

<script type="text/javascript"> 
   var compareWith = "{{someDjangoVariable}}";

and some where down the line

if(val === compareWith) {
Back to Top