MC2020
MC2020

Reputation: 47

Django passing variables dynamically from Views.Py to Jquery

I am struggling to understand this.

I have a dictionary titled alldicts that I am passing from Views in Django into the HTML. How do I then reference that dictionary to Jquery to autofill in input values in my HTML?

My code in Views.Py:

mydict1 = {
'one' : 1
'two' : 2
'three' : 3
}

mydict2 = {
'one' : 4
'two' : 5
'three' : 6
}

mydict3 = {
'one' : 7
'two' : 8
'three' : 9
}


alldicts={
'mydict1': mydict1,
'mydict2': mydict2,
'mydict3': mydict3
}

return render(request, self.template_name, alldicts)

In the HTML section of my code, I have a select dropdown with the options "mydict1","mydict2", and "mydict3". Below it I have three inputs (number of inputs will be dynamic, but wanted to give a simple example) that I want to auto fill to match the selected option. (IE if I select mydict2 in the dropdown, the inputs (#one, #two, and #three) will fill to be 4,5, and 6 respectively).

In html, if I try something like this, it doesn't work:

$("#hselect").change(function() {

var a = "{{alldicts}}";

var selectedValue = $(this).val();


$.each( a, function(idx, obj) {
   $.each( obj, function(key, value){
       if (selectedValue == idx) {                  
          $('#'+key).val(value);
       }
   });
});


}


<select id = "hselect" name="hselect" style="width: 250px;" onchange="changeoption();">
<option> mydict1 </option>
<option> mydict2 </option>
<option> mydict3 </option>
</select>

<input id='one' ><br>
<input id='two' ><br>
<input id='three' ><br>

This does not work. However if I pass the dictionary statically through the HTML, it does work. How do I pass dynamically from Views?

For example this does work:

$("#hselect").change(function() {

var a = {
'mydict1' = {'one' : 1, 'two' : 2, 'three' : 3},
'mydict2' = {'one' : 4, 'two' : 5, 'three' : 6},
'mydict3' = {'one' : 7, 'two' : 8, 'three' : 9},
};

var selectedValue = $(this).val();


$.each( a, function(idx, obj) {
   $.each( obj, function(key, value){
       if (selectedValue == idx) {                  
          $('#'+key).val(value);
       }
   });
});


}


<select id = "hselect" name="hselect" style="width: 250px;" onchange="changeoption();">
<option> mydict1 </option>
<option> mydict2 </option>
<option> mydict3 </option>
</select>

<input id='one' ><br>
<input id='two' ><br>
<input id='three' ><br>

The only thing that changes is how I pass the dictionary, mydicts, and define the variable a. How do I do this dynamically from Views.Py?

Upvotes: 0

Views: 940

Answers (2)

  1. You need ensure convert all datatype in alldicts from python object to string or number.

  2. Change alldicts in your views.py from python dict to json format:

import json
json_alldicts = json.dumps(alldicts)

For jinja template

var a = JSON.parse('{{ json_alldicts | tojson | safe }}');
console.log(a);

For django template

var a = JSON.parse('{{ json_alldicts | safe }}');
console.log(a);

Upvotes: 1

Bernhard Beatus
Bernhard Beatus

Reputation: 1216

The answer is quite tricky (updated my Answer)
Now its working dynamically. HTML

<div id="container"></div>
<div id="inputs"></div>

This is are your objects (console.log helps): Four dynamic I added a fourth element to the first mydict1

mydict1 = {
  'one': 1,
  'two': 2,
  'three': 3,
  'four': 4
}

mydict2 = {
  'one': 4,
  'two': 5,
  'three': 6
}

mydict3 = {
  'one': 7,
  'two': 8,
  'three': 9
}

alldicts = {
  'mydict1': mydict1,
  'mydict2': mydict2,
  'mydict3': mydict3
}

console.log('alldicts', alldicts);

These creates the dynamic select option box:

var markup = '';
markup += '<select id="hselect" name="hselect" style="width: 250px;">';
$.each(alldicts, function(idx, obj) {
  console.log('obj', idx);
  markup += '<option value="' + idx + '">' + idx + '</option>';
});

markup += '</select>';

$("#container").append(markup);

This is the changeHandler for changing the select options

var markupInputs = '';

$('#hselect').on('change', function() {
  $('#inputs').empty();
  console.log(this.value);
  var option = this.value;
  var elements = {};
  $.each(alldicts, function(idx, obj) {
    console.log('idx', idx)
    if (idx == option) {
      $.each(obj, function(idx1, obj1) {
         elements[idx1] = obj1;
      });
    }
  });
  console.log('arr2', elements);

  $.each(elements, function(index, value) {
    markupInputs += '<input id="' + index + '" value="' + value + '"></input><br>';
  });

  $("#inputs").append(markupInputs);
  markupInputs = '';
});

Upvotes: 0

Related Questions