Issue
This Content is from Stack Overflow. Question asked by Rheanna
I have a modal that works in most ways – it changes content based on which image is clicked… but it is firing twice on the backend and for the life of me I can’t find out why!!! This was basically taken directly from bootstrap’s documentation so I’m not sure where the problem is coming from. While it’s not a problem on the front-end it will cause issue moving forward with updating data, running ajax, etc. When the following code is run, the console prints the modalTitle twice. Where am I gong wrong?!?
It’s worth it to note that I have another modal on the page, but even when I’ve commented it out completely it didn’t fix the issue and I figured that I’m calling ONLY the modal with id="moveModal"
so not sure why that would be a problem anyway. Thank you for your help!
HTML Image that calls modal when clicked
<img data-bs-toggle="modal" data-bs-target="#moveModal" data-bs-card="{myCardNameHere}" class="viewCard" id="{cardIdHere}" src="{cardImgPathHere}">
HTML Modal
<div class="modal fade" id="moveModal" tabindex="-1" aria-labelledby="moveModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moveModalLabel">Move</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="moveForm" method="POST">
<input type="hidden" name="type" value="move">
<div class="modal-body">
<div class="mb-3">
<select class="form-control">
<option>1</option>
<option>2</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Move</button>
</div>
</form>
</div>
</div>
</div>
Script to update title
$(document).ready(function() {
var modal = document.getElementById('moveModal')
modal.addEventListener('show.bs.modal', function (event) {
var button = event.relatedTarget
var card = button.getAttribute('data-bs-card')
var modalTitle = modal.querySelector('.modal-title')
modalTitle.textContent = 'Move ' + card
console.log(modalTitle);
});
});
Solution
Answer
The code itself was just fine (as some pointed out in the comments) – I FINALLY realized that I had included the script file that includes the JS within a loop rather than outside of it as intended, causing the multiple modal fires.
Lesson learned – CHECK YOUR LOOPS!!
This Question was asked in StackOverflow by Rheanna and Answered by Rheanna It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.