javascript: Retrieve specific row data from Bootstrap Modal table and pass it back to the main webpage

I am a beginner in using bootstrap modals and JavaScript, and I need assistance in resolving the following issue.

Desired Outcome:

1. When the parent screen opens the modal window, it should display a form to find a username:

<div class="form-group">
    @Html.LabelFor(model => model.ManagerName, htmlAttributes: new { @class = "control-label col-md-2" })*
    <div class="col-md-10">
        @Html.EditorFor(model => model.ManagerName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ManagerName, "", new { @class = "text-danger" })
        <button type="button"
                class="btn btn-default"
                data-toggle="modal"
                data-target="#findByName"
                id="findManagerDetails">
            Find
        </button>
    </div>
</div>

<div class="modal" id="findByName" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
            </div>
            <div class="modal-body">
                @{ Html.RenderPartial("../Admin/Find"); }
            </div>
        </div>
    </div>
    <div id="validationSummary" class="validation-summary">
        <ul></ul>
    </div>
$("#findManagerDetails").click(function () {
    type = "Manager";
    var searchName = $("#ManagerName").val();
    console.log(searchName);
    document.getElementById("Search").value = searchName;
    document.getElementById("SearchBtn").click();
});

2. The Modal Dialog will display a list of user IDs based on the searched username:

$(document).ready(function () {
    $("#clear").click(function () {
        document.getElementById("Search").value = "";
        var SetData = $("#DataSearching");
        SetData.html("");
    });
    $("#SearchBtn").click(function (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        var SearchValue = $("#Search").val();
        var SetData = $("#DataSearching");
        SetData.html("");
        $.ajax({
            type: "get",
            url: "@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")Admin/GetByIFName?name=" + SearchValue,
            contentType: "html",
            success: function (result) {
                console.log(result);
                $("#DataSearching").empty();
                if (result.length == 0) {
                    SetData.append('<tr style="color:red"><td colspan="3">No Match Data</td></tr>')
                } else {
                    $.each(result, function (index, value) {
                        var Data = "<tr>" +                                   
                            "<td><a href=?id=" + value.UserID + "# onclick='SetName();'>" + value.UserID + "</a></td>" +
                            "<td>" + value.UserName + "</td>" +
                            "<td>" + value.Email + "</td>" +
                            "</tr>";
                        
                        SetData.append(Data);

                    });
                }
            }
        });
    });

3. Upon selecting one of the rows in the Modal dialog, the selected userid, username, and email will be returned to the parent screen:

function SetName() {
    const urlParams = new URLSearchParams(window.location.search);
    userid = urlParams.get('id');

    console.log("Selected ID:" + userid);

    if (type == "Manager") {
        document.getElementById("ManagerID").value = userid;
        document.getElementById("btnValidateManagerID").click();
    }

    if (type == "Interviewer") {
        document.getElementById("InterviewerID").value = userid;
        document.getElementById("btnValidateInterviewerID").click();
    }

    if (type == "Interviewer1") {
        document.getElementById("Interviewer1ID").value = userid;
        document.getElementById("btnValidateInterviewer1ID").click();
    }

    $("#findByName").modal("hide");
}

Question: How can I transition from step 2 to step 3?

Thank you.

Answer №1

credits:Source

Here is the updated code snippet that demonstrates how to pass data from a modal dialog back to parent screen controls, addressing point 3.

<script>      
    $(document).on('click', '#DataSearching tr', function () {
        var tableData = $(this).children("td").map(function () {
            return $(this).text();
        }).get();

        //alert("Your data is: " + type + " , " + $.trim(tableData[0]) + " , " + $.trim(tableData[1]) + " , " + $.trim(tableData[2]));
        if (type == "Manager") {
            document.getElementById("ManagerID").value = $.trim(tableData[0]);
            document.getElementById("ManagerName").value = $.trim(tableData[1]);
            document.getElementById("ManagerEmailAddress").value = $.trim(tableData[2]);
        }
        
        $("#findByName").modal("hide");
    });

</script>

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

Can we incorporate various CSS libraries for individual components on our React site?

Let's say, I want to use different CSS libraries for each of my components - Home, About, Contact. Would it be feasible to utilize material ui for Home, semantic ui for About, and bootstrap for Contact? If so, what is the process for incorporating t ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

Unpacking the Mechanics of JavaScript Functions

My goal is to simplify my code by breaking it down into multiple files. A successful example of this is: socket.once("disconnect", disconnectSocket); Then I have a separate function named disconnectSocket that can access the socket object like this: con ...

Merging JSON objects within an array using Node.js

When calling a function that returns an array with JSON objects, I encountered this issue: return new Promise((resolve) => { fileImport(userImport) .then ((response) => { console.log(response); resolve(response); }) }) result: ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Setting up lint-staged for Vue projects: A step-by-step guide

After setting up a new Vue3 app using the Vue CLI and configuring Prettier as my linter, I decided to implement commitlint, husky, and lint-staged for validating commit messages and linting the code before pushing it. My Approach Following the instructio ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Utilizing a MONGO_URL to efficiently run multiple Meteor applications on a single server

I have successfully deployed a Meteor application on my Ubuntu server using Meteor Up (MUP) and everything is working well. However, when attempting to deploy a second app on the same server, I encounter issues with connecting to MongoDB. The error message ...

Is there a way to load JSON data into charts through an AJAX request?

Is there a way to pass JSON data to a JSP file and populate it into the charts data directly without setting each value using a model attribute? In my EmployeeController, I have a lineBarChart method that currently sets data values individually. Here' ...

Deleting a page reference from the page history stack in Angular 4

I am working on my angular web application and I am looking for a way to remove a specific page reference from the angular page history stack. For example, if I navigate from the login page to the dashboard page, I want to remove the login page reference f ...

showcasing a map on an HTML webpage

Seeking advice on integrating a map feature in HTML to mark store locations. Working on an app for a business community and need help with this specific functionality. Your assistance would be greatly appreciated! ...

Creating a search API using Codeigniter: A step-by-step guide

I have experience creating a Search API using native PHP, but I am unsure how to implement it in Codeigniter. The code provided below is not returning the desired data. Can someone please guide me in the right direction? public function peta(){ $dat ...

Implement a feature where users can add text inputs to specific columns in a table by

Recently, I've been diving into jquery table manipulation. I've written a code snippet that is supposed to add a text input field to a specific column when clicked. In my case, the column is the 9th. Here's the code I have so far: $('# ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

Analyzing Variables Against SQL Columns in PHP

I'm trying to compare a variable to a column in my table and execute a query if the condition is met. Here's my PHP code, how should I modify it? $money_to_send = $_POST["money_to_send"]; $num_ban = $_POST["num_ban"]; if ($money_to_send < $so ...

Ways to retrieve the output from an AJAX call

Today I'm developing a JavaScript function named "sendData". This function simplifies the process by eliminating the need to manually code an entire ajax statement. However, considering that it operates asynchronously, I found myself wondering how to ...

Transferring information to a JSON file using ActionScript 3

My client is unable to provide full access to his database for security reasons, so he suggested using a REST/JSON service with a specific key to post the data. The URL provided by him should allow identification of all data coming from my app. Here is wh ...

How can I retrieve data from all Holding Registers in a Modbus Slave device?

I'm utilizing a Delta PLC that supports Modbus232 communication. The holding registers that contain data are not in sequential order. For example: 4246,6622,6626,6676,6624,6496,6658,4096,4346. Therefore, I have to make separate requests to read eac ...

Unable to retrieve the initial return value from the function that has been promisified

Previously, the code functioned correctly but was not properly promisified. const express = require('express'); function runServerAndReturn() { app = express(); console.log('Before starting server'); const server = app.lis ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...