The functionality of passing an ID in Bootstrap Modal is not functioning as expected

I'm facing an issue with passing an ID to my modal.

My goal is to have the details of an event displayed in the modal when the corresponding link (which represents the event) is clicked. However, I'm struggling to retrieve the ID and show the event name in the modal...

I tried implementing a solution from a post on Stack Overflow, but unfortunately, the outcome remains negative...

@model jak.formulaire.Models.Events

<div class="container">
    @* Datatable of Events member *@
    <div>
        <table id="example" class="table table-hover" style="width:100%; margin-top:2%">
            <thead>
                <tr>
                    <th scope="col">Event Name</th>
                    <th scope="col">Start Date</th>
                    <th scope="col">End Date</th>
                    <th scope="col">Status</th>

                </tr>
            </thead>
        </table>
    </div>
</div>

@* Modal Details *@
<div class="modal" role="dialog" id="myModal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Details</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

                <div id="myModalContent">
                    <form id="myForm">
                        <div class="form-horizontal">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Event_Name, htmlAttributes: new { @class = "control-label col-md-4" })
                                <div class="col-md-8">
                                    @Html.EditorFor(model => model.Event_Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Name", @id = "Name" } })
                                </div>
                                @Html.ValidationMessageFor(model => model.Event_Name, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </form>
                </div>


                <p>Modal body text goes here.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary">Save changes</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


@section Scripts{

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>

    <script>
        $(document).ready(function () {
            $('#example').DataTable({

                ajax: {
                    "url": '@Url.Action("GetHistoric", "Events")',
                    "dataSrc": "",
                    "type": "GET",
                    "datatype": "json"
                },
                columns: [
                    {
                        'data': 'Name', "render": function (data) {
                            return '<a href="#" class="open-Details" data-toggle"modal" data-id="' + data + '" id="' + data + '">' + data + '</a>';
                        },
                    },
                    { 'data': 'Date_Begin_cU' },
                    { 'data': 'Date_End_cU' },
                    { 'data': 'Status' },

                ],
                "paging": false,
                "info": false,
                "searching": false
            });
            $(document).on("click", ".open-Details", function () {
                $('#Name').val(this.id);
                $('#myModal').modal('show');
            });


        });
    </script>
}

Answer №1

Here is an example:

data-id="data" id="' + data + '"

is included in your jQuery code when trying to retrieve an id from a data attribute:

$('#Name').val($(this).data('id'));

This should be corrected to:

data-id="'+data+'" id="' + data + '"

so the entire line should be:

return '<a href="#" class="open-Details" data-toggle"modal" data-id="'+data+'" id="' + data + '">' + data + '</a>';

After making this adjustment, the following:

$('#Name').val($(this).data("id"));

will work properly.

You can either set the data variable instead of the "data" literal, or use this.id like this:

$('#Name').val(this.id);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...

Ensure that the initial section of the page spans the full height of the browser, while all subsequent sections have a

I have a website composed of various blocks with different heights, all extending to full width. My goal is to make the first block the full height and width of the browser window, while keeping the other blocks at a set height as seen on this site: After ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

What is the best way to display a div beneath the highlighted text within a textarea field?

I have encountered a situation where I want to display a div (like a popup) when text is selected in a text area. However, when using mouse-down for this action, the position of the div sometimes does not align directly below the selected text. Below is t ...

Using JavaScript to submit the value of a checkbox

I'm currently working on a form submission using JavaScript that includes both text input and two checkboxes. <script> function SubmitFormData() { var preferredLocation = $("#preferred_location").val(); var relocation = []; ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

The upcoming tick override feature will execute the specified function

I am looking to replace the code below The function will run in the following tick req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 5); } : function (fn) { fn(); }; with this new code, window.require.nextT ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

What is the best method to organize HTML tables in Knockout by utilizing a Breeze navigation property?

Currently, I am utilizing Breeze.js to manage my data model within Knockout.js. This involves a simple view model with an adapter library for handling sorting tables on entity properties. The tables are sorted using tablesorter, along with a knockout bindi ...

Executing a node module in a web browser

I'm attempting to upload and read an Excel file with the help of a node module called read-excel-file. Following the instructions for usage in the browser, I have added the following code snippet to my .js file: import readXlsxFile from 'read-ex ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

jquery is in motion while svg paths are at a standstill, waiting to

i have been attempting to incorporate a css-animated svg into my project. initially, the animation would start automatically, which was undesirable. after some research, i discovered that by declaring it as paused and then triggering it using jQuery with $ ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

Discovering the appropriate ASP.NET MVC View to display can be achieved by using return View("viewName", model) instead of the typical return View(model)

My mvc site is functioning well on both mobile and non-mobile browsers. However, I am facing an issue with a couple of Actions where I do not want to use return RedirectToAction(...); for logging purposes. Instead, I have been using return View("OtherView" ...

Generate a 2D matrix to represent a grid

I have a list of numbers that I need to convert into a two-dimensional array. For example: let data=['1','4','2','1','6','9','1','5',] The desired output would be: result = ...

Does LABJS include a feature for executing a callback function in the event of a timeout during loading?

When using LabJS to asynchronously load scripts with a chain of dependencies, if one of the scripts breaks (due to download failure or connection timeout), it seems that the remaining scripts in the chain will not be executed. Is there a way to define a ...

Tips for embedding a hyperlink in your HTML website

While I've mastered adding images to my HTML website, there's one thing that still eludes me despite scouring numerous online resources. I recently created a small animation using JavaScript on a different IDE, and I have the link to my output: ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

What is the advantage of using event.target over directly referencing the element in eventListeners?

Suppose there are several buttons in an HTML file and the following code is executed: const buttons = document.querySelectorAll('button'); buttons.forEach((btn) => { btn.addEventListener('click', (e) => { console.log(btn.te ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...