[Answered ]-Passing data to modal from button

1👍

To pass the values from the button to the modal and then to the JavaScript function, you need to make a few adjustments in your code.

Update the modal trigger buttons to include the data attributes:

<button type="button" class="btn btn-sm btn-success accept-btn" data-toggle="modal" data-target="#acceptModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Accept</button>
<button type="button" class="btn btn-sm btn-danger reject-btn" data-toggle="modal" data-target="#rejectModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Reject</button>

Update the modal to use event.relatedTarget to access the button that triggered the modal. This way, you can extract the data attributes from the triggering button:

<div class="modal fade" id="acceptModal" tabindex="-1" role="dialog" aria-labelledby="acceptModalLabel" aria-hidden="true">
    <!-- ... other modal code ... -->
    <div class="modal-body">
        <!-- Add content for the Accept modal here -->
        Are you sure you want to accept this proposal?
        This action cannot be undone!
        <p>Supervisor ID: <span id="modalSupervisorId"></span></p>
        <p>Proposal ID: <span id="modalProposalId"></span></p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-success accept-btn-modal">Accept</button>
    </div>
</div>

Update the JavaScript to handle the show.bs.modal event to extract and set the data attributes when the modal is shown:

$('#acceptModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    var supervisorId = button.data('supervisor-id');
    var proposalId = button.data('proposal-id');

    // Set the data in the modal
    $('#modalSupervisorId').text(supervisorId);
    $('#modalProposalId').text(proposalId);

    // Attach the data to the Accept button in the modal
    $('.accept-btn-modal').data('supervisor-id', supervisorId);
    $('.accept-btn-modal').data('proposal-id', proposalId);
});

// Update the acceptProposal function to use the data from the modal button
function acceptProposal() {
    var supervisorId = $('.accept-btn-modal').data('supervisor-id');
    var proposalId = $('.accept-btn-modal').data('proposal-id');

    // Rest of your AJAX code...
}
👤Rem

Leave a comment