Reputation: 589
I want to display selected user name.
template
<select class="form-control" name="user_id">
{% for user in user_list %}
<option value="{{ user.id }}">{{ user.id }}</option>
{% endfor %}
</select>
<div>
"I want to display name of selected user here"
</div>
views.py
class UsersView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["user_list"] = [
{"id": "0", name: "A"},
{"id": "1", name: "B"},
{"id": "2", name: "C"},
]
return context
template_name = "users.html"
How Can I access selected data in template?
Upvotes: 0
Views: 63
Reputation: 758
You can achieve this using pure js,
1) Give your dropdown an id
& add a onchange
event
<select class="form-control" name="user_id" id="my_dropdown" onchange="updateUser()">
{% for user in user_list %}
<option value="{{ user.id }}">{{ user.id }}</option>
{% endfor %}
</select>
2) Put "I want to display name of selected user here"
inside div
or span
<span id="selected_user"> "I want to display name of selected user here" </span>
3) Create the func which you used in onchange, which'll put the selected value of dropdown into the span
which we created above.
function updateUser() {
document.getElementById("selected_user").innerHTML = document.getElementById("my_dropdown").value;
}
I hope this was clear to you, if not let me know.
Upvotes: 1