I have a foreach loop which goes trough a list of rules with each rule having a bootstrap dropdown to edit the rule. The dropdown link should open a modal, which it does.
The problem is that the event.relatedTarget always has the data from the first dropdown item instead of the actual dropdown item that has been clicked. If I remove the dropdown and just use normal links everything works fine how it should.
What am I doing wrong here?
The loop with dropdown:
@foreach( $rules as $rule )
<a href="#" OnClick="event.preventDefault();" role="button" id="dropdownMenuLink{{ $rule->id }}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-offset="-1,8">{{ $rule->name }} <i class="fas fa-caret-down"></i></a><br />
<ul class="dropdown-menu" aria-labelledby="dropdownMenuLink{{ $rule->id }}">
<li><a class="dropdown-item" href="#" OnClick="event.preventDefault();" data-toggle="modal" data-target="#editRule" data-id="{{ $rule->id }}" data-name="{{ $rule->name }}">Edit rule</a></li>
</ul>
@endforeach
The modal:
<div class="modal fade" id="editRule" tabindex="-1" role="dialog" aria-labelledby="editRuleCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content text-white bg-dark">
<form method="POST" action="#">
@csrf
<div class="modal-header">
<h5 class="modal-title" id="editRuleCenterTitle">Edit Rule</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<div class="col-md-12">
<label for="ruleName" class="form-label">Rule name</label>
<input id="ruleName" type="text" class="form-control" name="ruleName" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update Rule</button>
</div>
</form>
</div>
</div>
</div>
The script:
@section( 'scripts' )
<script>
$( '#editRule' ).on( 'show.bs.modal', function ( event ) {
console.log( event.relatedTarget );
var button = $( event.relatedTarget );
var id = button.data( 'id' );
var name = button.data( 'name' );
var modal = $( this );
modal.find( '.modal-title' ).text( 'Edit rule: ' + name );
modal.find( '.modal-body input' ).val( name );
});
</script>
@endsection
``