I am creating a edit post button in which the user clicks the button and a modal with the form pops up to edit the form. For some reason, only the button on the first post will work and open the modal. Not sure what i'm doing wrong and any help would be greatly appreciated. Thanks in advance.The post form in the modal is for testing.
home.php:
@if($posts)
@foreach($posts as $post)
<div class="card" style="margin-top: 20px">
<div class="card-header">
<div>{{$post->user->name}}</div>
<div id="post-date">{{$post->created_at->diffForHumans()}}</div>
</div>
<div class="card-body">
<div>{{$post->body}}</div>
@if(!empty($post->photo_id ))
<img class="post-image"src="/images/{{ $post->photo->file }}" alt="">
@else
<img class="post-image" src="http://placehold.it/400x400" alt="">
@endif
<div class="card-footer">
<div>
<button class="btn-primary btn-sm" id="edit-post-btn">Edit Post</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form method="POST" enctype="multipart/form-data" action="{{ route('makePost') }}">
@csrf
<div class="form-group row">
<label for="body" class="col-md-4 col-form-label text-md-right">{{ __('Body') }}</label>
<div class="col-md-6">
<input id="body" type="text" class="form-control" name="body" value="{{ old('body') }}">
</div>
</div>
<div class="form-group row">
<label for="photo" class="col-md-4 col-form-label text-md-right">{{ __('Photo') }}</label>
<div class="col-md-6">
<input id="photo" type="file" class="form-control" name="photo_id" value="{{ old('photo') }}">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Submit Post') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
@endforeach
@endif
JS file:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("edit-post-btn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
}