Implementing a Bootstrap pop-up Model using JavaScript: A Step-by-Step Guide

I am looking to trigger a Bootstrap Pop-Up Model using a JS function, passing values from the function. When the user clicks on update, I want to return to the JS function and update the values; if they press cancel, nothing should happen.

@using (Html.BeginForm("BulkUpdate", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
<div class="container col-md-12">
    <table id="myTable" class="cell-border compact hover">
        <thead>
            <tr>
                <th>@Html.DisplayNameFor(m => m.First().Id)</th>
                <th>@Html.DisplayNameFor(m => m.First().TagName)</th>
                <th>@Html.DisplayNameFor(m => m.First().TagCategory)</th>
                <th>@Html.DisplayNameFor(m => m.First().TagValue)</th>
                <th> Action</th>
            </tr>
        </thead>
        <tbody>
            @for (int i = 0; i < Model.Count(); i++)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(m => Model[i].Id)
                        @Html.HiddenFor(m => Model[i].Id)
                    </td>
                    <td>
                        @Html.DisplayFor(m => Model[i].TagName)
                    </td>
                    <td>
                        @Html.DisplayFor(m => Model[i].TagCategory)
                    </td>
                    <td>
                        @Html.EditorFor(m => Model[i].TagValue, new { htmlAttributes = new { @id = "TagVaule_" + Model[i].Id, @class = "form-control" } })
                    </td>
                    <td>
                        <button type="button" class="btn btn-secondary" onclick="UpdateRow(@Model[i].Id)">Update</button>
                    </td>
                </tr>
            }

        </tbody>
    </table>
    <div id="myModal" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <label id="tagValueLabel"></label>
                <button onclick="Cancel()">cancel</button>
                <button onclick="Confirm()">confirm</button>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Bulk Update" class="btn btn-secondary" />
        </div>
    </div>
</div>

}
@section Scripts{
    <script>
        $(document).ready(function () {
            $('#myTable').DataTable();
        });
    </script>


    <script>
        debugger;
            var tagvalue = '';
            var id = '';

            function UpdateRow(id)
            {
                this.id = id;
                tagvalue = $("#TagVaule_" + id).val();
                DisplayModal(tagvalue);
            }

            function DisplayModal(value)
            {
                $("#tagValueLabel").text(value);
                $("#myModal").modal('show');
            }

            function Cancel()
            {
                $("#myModal").modal('hide');
            }

            function Confirm()
            {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Update","Home")',
                    data: {
                        id: id,
                        value: tagvalue
                    },
                });
                $("#myModal").modal('hide');
            }

    </script>
}

Currently relying on the built-in confirm function, but now aiming to implement a Bootstrap model that displays the tag value and its corresponding old value in a pop-up model. Upon user click on update, the submission should commence. Thanks for your assistance!

Answer №1

If you want to execute a task when the confirm button is clicked on a modal, one approach is to directly perform the required actions within the Confirm function.

Here is the JavaScript code:

var bootStrapId=0;
var tagvalue = 0;

function UpdateRow(id) {
    tagvalue=$("#TagVaule_" + id).val();
    bootStrapId=id;
    DisplayModal();
}

function DisplayModal() {
    $("#myModal").modal('show');
}

function Cancel() {
    $("#myModal").modal('hide');
}

function Confirm() {
    $.ajax({
        type: "POST",
        url: '@Url.Action("Update","Home")',
        data: {
            id: bootStrapID,
            value: tagvalue
        },
    });
    $("#myModal").modal('hide');
}

And here is the HTML structure:

<div id="myModal" class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
        <button onclick="Cancel()">cancel</button>
        <button onclick="Confirm()">confirm</button>
    </div>
  </div>
</div>

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

Failed to read the JSON file

Upon accessing The browser displays the following content: [ {"title": "simple node (no explicit id, so a default key is generated)" }, {"key": "2", "title": "item1 with key and tooltip", "tooltip": "Look, a tool tip!" }, {"key": "3", "title": "<span& ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

JavaScript Stopwatch Break

Below is the code snippet. How can a button be implemented to pause the timer and then resume it when the resume button is pressed? The // marks indicate where I plan to add my pause and resume functionality. Thank you in advance for your assistance! &l ...

Is there a way to change a parent's style for only one specific child?

Currently, I am developing an application with a primary layout that utilizes the bootstrap class "container-fluid". <main class="container-fluid"> [....] //a child div where I'd like to remove the parent's padding for this div ...

Addressing file routes within my personalized npm bundle

I am in the process of developing a custom npm package called packer and experimenting with a configuration similar to webpack, where users can install my CLI tool to build their packages. Here is an example of a package.json file for a test package using ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Error 415: Media Type Not Supported within Model-View-Controller

I encountered this particular error for the first time during my work. My project is based on .Net Core 2.1 MVC. The error occurs when attempting to log in, and there is nothing out of the ordinary about it. Just a simple AccountController and login form a ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

What is the best way to position a collection of images together for optimal

I'm a new web developer and I'm struggling with aligning images on my page. I've added the images successfully, but I want them to fill the entire space of the previous div. I'm not concerned about the aspect ratio, just the alignment. ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Running a jQuery function that triggers a PHP script when the page

Hi there! I'm currently working on implementing jQuery's ajax feature to call a php script when the page loads. This php script will fetch xml data from a web service URL, parse it, and then display specific parts of it within a div tag on the pa ...

When using sequential jQuery 'pages', an error referencing the third frame occurs

I am new to using javascript/jquery and have been experimenting with the w3schools tutorials and jquery documentation. I created a page where user input is accepted and javascript prints output based on that input. I tried modifying it to work sequentially ...

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Tips for utilizing the computed property to search and filter the `ul` content in Vue based on user input

Is there a way to utilize the computed property in order to achieve this? I want the ul element to only display the li items that include my input. For instance, if I type "Ad" into the input field, only the "Add some todos" li item should be displayed. An ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

How can I retrieve objects using the JSON function?

I need to design a function that returns objects like the following: function customFunction(){ new somewhere.api({ var fullAddress = ''; (process address using API) (return JSON data) })open(); } <input type= ...

Is it possible to use async/await with the React setState method?

Seeking clarification on the use of async/await in React setState method. I previously believed it only functioned with Promises, but I have not found any definitive documentation supporting this. Any assistance would be greatly appreciated! In my applica ...

The process of displaying custom number buttons on the correct input field in react.js

I am facing a challenge in implementing this feature. I have created custom number buttons from 0-9 that users can click on instead of using the keyboard. The issue arises when there are multiple dynamically generated input fields based on JSON Data. For e ...