Django Javascript preselected value from database
I have a series of drop downs that are dependent upon the one above it. Starting with 'state' then pulls a list of all cities for that state and then all schools in that city.
I am trying to find a way that when a user wants to update this information that it will pull the current information from the database and then have that value preselected from the list. Currently it just shows the 'Choose a state' the whole time until selected. If the user is from Maine, I want that to be selected already.
Also, if possibly, how to make this an if statement. That if the user's state is null, then 'Choose state' is displayed and if not null, display current state.
Thank you very much for the help!
views.py
def get_json_state_data(request):
qs_val_unsorted = list(States.objects.values())
qs_val = sorted(qs_val_unsorted, key=lambda d: d['name'])
return JsonResponse({'data':qs_val})
display.html
<div class="ui fluid search selection dropdown" id='states_dropdown'>
<input type="hidden" name="state">
<i class="dropdown icon"></i>
<div class="default text" id="state_text">Choose a state</div>
<div class="menu" id='state_data_box'> </div>
</div>
main.js
$.ajax({
type: 'GET',
url: '/register/states-json/',
success: function(response){
const states_data = response.data
states_data.map(item=>{
const option = document.createElement('div')
option.textContent = item.name
option.setAttribute('class', 'item')
option.setAttribute('data_value', item.name)
statesDataBox.appendChild(option)
})
},
error: function(error){
console.log(error)
}
})