0

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.

  • If I understand right, you cannot pass value from client side to already rendered template. – ch4nd4n Dec 21 '22 at 06:30
  • In this case, how can I pass it? can you suggest? – MD. RONY AHMED Dec 21 '22 at 06:32
  • Can you explain a bit more what you are trying to do. If your question is that you want to pass value from JavaScript to Django template. AFAIK, answer is no you cannot do that. You will have to make a work around to up update whatever you are via XHR or something. – ch4nd4n Dec 21 '22 at 06:34
  • Actually, I have a id in the above mentioned input field value="1". I need to compare agent.id == that id (value="1"). How to do? – MD. RONY AHMED Dec 21 '22 at 06:47

1 Answers1

0

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) {
ch4nd4n
  • 4,110
  • 2
  • 21
  • 43