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.

<!DOCTYPE HTML>
 <HTML>
   <body>
    <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="{{ agent.id }}" {% if agent.id == delivery_agency_id  %} selected="selected" {% endif %}>{{ agent.name }}
  </option> {% endfor %}
</select>

<script>
  var delivery_agency_id = document.getElementById("agency_id").value;
  alert(delivery_agency_id )
</script>

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}}";
</script>

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

https://jsbin.com/guvugipoji/edit?html,js,output

Important parts are

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

and

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}}";
</script>

and some where down the line

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