As my title already says, I have an issue with a modal not opening on all buttons.
Here is the situation:
I have a page that displays all applications a user has sent for different jobs. So it may be just one, or up to whatever. It looks like this:
Now if the user wants to cancel the application he can press the button "Bewerbung zurückziehen", then the modal opens to give a heads up that all data will be lost and if he is sure, in the modal he can confirm it or go back. Everything works fine for the first post on the site, but for all other posts just nothing happens, so the modal doesn't open.
Here is my code:
- The blade file that displays all posts:
@foreach($bewerbungen as $bewerbung)
@foreach($stellenanzeigen_names as $stellenanzeigen_name)
@if($bewerbung->Stellenanzeigen_ID === $stellenanzeigen_name->Stellenanzeigen_ID)
<div
>
<!--Card 1-->
<div
>
<div >
{{ $stellenanzeigen_name->Titel }}
<hr >
</div>
<div >
ID der Bewerbung: {{ $bewerbung->Bewerbung_ID }}</div>
<div >
ID der Stellenanzeige: {{ $bewerbung->Stellenanzeigen_ID }}</div>
<div >
<div >
<button type="submit" id="delete_appl_btn" name="delete_appl_btn"
>
Bewerbung zurückziehen
</button>
</div>
</div>
</div>
</div>
@endif
@endforeach
@endforeach
Here is the code for the modal:
<div id="delete_application_modal" >
<div >
Bewerbung zurückziehen
<div >
</div>
</div>
<div >
<label for="delete_application" >Bewerbung zurückziehen</label>
<form action="{{ route('delete', $bewerbung->Bewerbung_ID) }}" method="post">
@csrf
<button type="submit" id="ok_btn" >
Bewerbung zurückziehen
</button>
</form>
</div>
<div >
<button id="back_btn_tel" >
zurück
</button>
</div>
</div>
@if(session()->has('message'))
<div >
{{ session()->get('message') }}
</div>
@endif
<script>
var delete_appl_modal = document.getElementById("delete_application_modal");
var open_modal = document.getElementById("delete_appl_btn");
var back_btn = document.getElementById("back_btn_tel");
open_modal.onclick = function () {
delete_appl_modal.style.display = "block";
}
back_btn.onclick = function () {
delete_appl_modal.style.display = "none";
}
window.onclick = function (event) {
if (event.target == modal) {
delete_appl_modal.style.display = "none";
}
}
</script>
Honestly, I have zero clue why it works for the first but not for the others, they have the same buttons, with the same name, id & everything. Maybe one of you had a similar issue. I wish you all happy holidays!
CodePudding user response:
The id
property is expected to be unique within a page, so when using getElementById
once an element with that id
has been located it doesn't continue searching for others.
As you have multiple button
elements that you want to target, you will need to us something like querySelectorAll
or getElementsByClassName
to target every element that should trigger the modal to open.
CodePudding user response:
Agree with Peppermintology's answer.
You should use class name instead of using id. because id is unique