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?