Eden WebStudio Eden WebStudio -4 years ago 43
Javascript Question

Pass variable id into Modal

I have used this code to load a list of IDs in a foreach loop into a modal. I am have an issue where only the first ID is being populated rather than the ID for the clicked element. What is the correct var to set on appointment ID so that it loads the related id.

$('#appointmentModal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var appointmentID = ($('[data-id]').val());
//populate the textbox
$(e.currentTarget).find('input[name="appointmentID"]').val(appointmentID);
});


Button

<button type="button" class="btn btn-sm btn-teal " data-toggle="modal" data-target="#appointmentModal" data-appointment="{{ $item->appointmentID }}" data-id="{{ $item->appointmentID }}" id="appointmentID" value="{{ $item->appointmentID }}">
<i class="fa fa-edit"></i> {{ trans('translate.edit') }}
</button>

Answer Source

Suggestion:

I would suggest to get the value of your DOM element click like this:

$(document).ready(function() {
    $('.btn-teal').click(function() {
        // 1) Use .attr() method to get the given value based on what [attribute] (e.g data-id)
        // This will get the appointment value of the element click
        var appointmentID = $(this).attr('data-id'); 

        // 2) Then by the time you open the modal, You can assign it
        // on another DOM element
        $('#appointmentModal').find('input[name="appointmentID"]').val(appointmentID);

        // 3) After assigning it, Open that modal box
        $('#appointmentModal').modal('show');
    });
});

Hope this helps for your case

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download