I have a dropdown that triggers an AJAX call when a new value is selected. The AJAX script calls my Django view, which returns a variable (a list of values). It seems to work until the step where I need to fill a second dropdown with the values from that list. I couldn't figure out how to do this.
Here is my html code:
<form class="wrapper" action="" method="post"> {% csrf_token %}
<select name="myVal" class="toChange">
<option val="1">1</option>
<option val="2">2</option>
</select>
<select id="dep" name="dep"> </select>
<script type="text/javascript">
function dropdownChange () {
var selectedValue = $(".toChange option:selected").val();
$.ajax({
url: '/myApp/templates/3/',
type: 'POST',
data: {'myVal': selectedValue},
success: function(result) {
alert(result);
}
});
}
$(".toChange").change(dropdownChange);
</script>
</form>
And here is my views.py file:
@csrf_exempt
def MyView3(request):
if request.method == 'POST' and request.is_ajax:
myVariable = json.dumps(["1", "2", "3", "4", "a"])
return HttpResponse(myVariable , content_type='application/json')
else:
return render(request,'home3.html')
When I select a new value in my dropdown, it triggers the AJAX call and the alert(result) line returns "1,2,3,4,a". So this part works, but I don't know how to populate with these values my "dep" dropdown.
I've been trying to insert the following code in the script, but it didn't produce any results:
var select = document.getElementById("dep");
var options = result
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
I'm not sure if this code was simply misplaced, or if it's just not the right one to use. Does anyone know what I should be doing here? Thanks
You can do it much simpler in success
attribute of ajax request:
success: function(data) {
var str = '';
data.forEach(function(opt){
str += '<option value="' + opt + '">' + opt + '</option>';
});
document.getElementById("dep").innerHTML = str;
}