Reputation: 43
I am tying to use jQuery in my Django template. When I click my #edit-website-btn
button nothing happens. Inside the console there aren't any errors. What is wrong?
<!-- in <head> -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script>
$(function () {
$('#edit-website-btn').click(function () {
$('#account-website').hide();
});
});
</script>
<!-- in <body> -->
{% for account in accounts %}
<tr>
<td>
<div id="account-website">{{ account.website }}</div>
<button type="button" class="btn btn-outline-primary" id="edit-website-btn">
Edit
</button>
<form id="website-form" class="hidden">
<input type="text" id="new-website" name="new-website">
</form>
</td>
</tr>
{% endfor %}
Upvotes: 1
Views: 397
Reputation: 337637
The issue is because your Django loop which outputs the HTML is creating multiple elements with the same id
, which is invalid. You can fix this by using common classes instead, then using DOM traversal in jQuery to relate the elements when the button is clicked. Try this:
<td>
<div class="account-website">{{ account.website }}</div>
<button type="button" class="btn btn-outline-primary edit-website-btn">
Edit
</button>
<form id="website-form" class="hidden">
<input type="text" class="new-website" name="new-website">
</form>
</td>
$(function () {
$('.edit-website-btn').click(function () {
$(this).siblings('.account-website').hide();
});
});
Upvotes: 2