"Utilizing the Bootstrap framework to enhance the functionality

I have a bootstrap table containing data that needs to be edited, with certain fields not displayed in the table.

To enable editing, I have added an edit button to each row along with a modal form. The button successfully loads the modal form without any issues.

There are 3 questions I have:

  1. How can I load the modal form with the data corresponding to the row associated with the clicked button?
  2. What is the process for saving the edited data when the save button within the modal is clicked?
  3. How do I refresh the table after the modal closes upon clicking the save button?

While I believe a tutorial would be beneficial, I am unable to locate one at the moment.

The current code for the button is as follows:

<button type="button" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#checkInModal">Check In</button>

Below is the current code snippet for the modal (with irrelevant fields removed for brevity):

  <!-- Modal -->
    <div class="modal fade" id="checkInModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Check In</h4>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

Answer №1

Take a look at this jsfiddle

Question 1: The task at hand involves finding the parent row, extracting necessary data, and assigning values to the inputs. Utilizing frameworks like handlebars or underscore.js can simplify this process by using templates to populate the DOM.

var elButton = $(this);
var id = elButton.data('id');
var row = elButton.closest('tr');        
var data = {
    firstName: row.find('.firstName').text(),
    lastName: row.find('.lastName').text(),
    handle: row.find('.handle').text(),
    id: id        
}

Question 2: (Please clarify if referring to database). To save data from the modal, follow a similar approach as with the row. Select the relevant values from the modal, send them through an HTTP request to your server.

var data = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    handle: $('#handle').val(),
    checkinId: $('#checkinId').val()
};

$.ajax({
    type: "POST",
    url: "http://yoururl.io/api/location",
    data: data
});

Question 3: (Assuming data is sourced externally). Implement a function that retrieves data via HTTP request. Trigger this function periodically to update the table with the latest information fetched from the datasource.

// Populate the table
$.ajax({
    type: "GET",
    url: "http://yoururl.io/api/location",
    success: function(data) {
        // Update the table by iterating over the response items and creating appropriate table cells
    }

});    

Answer №2

Check out this interactive fiddle solution for your issue.

You can view the example on JSFiddle by following this link: https://jsfiddle.net/YameenYasin/gk22kvyw/17/

In this demonstration, I have set up a sample table containing two columns - Name and Address. Each row has an Edit button that triggers a popup modal display. I've also included a hidden radio button to indicate the selected row.

<table class="table table-bordered table-stripped">
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Action</th>
    </tr>
    <tr>
        <td class="name">Name1</td>
        <td class="address">Address1</td>
        <td class="edit"><a href="javascript:void(0);">Edit</a>
            <input hidden type="radio" name="select">
        </td>
    <tr>
    <tr>
        <td class="name">Name2</td>
        <td class="address">Address2</td>
        <td class="edit"><a href="javascript:void(0);">Edit</a>
            <input hidden type="radio" name="select"></td>
    <tr>    
</table>

<!-- Modal -->
    <div class="modal fade" id="checkInModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Check In</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <label>Name:</label>
                            <input type="text" class="form-control" id="editName">
                        </div>
                        <div class="col-md-12">
                            <label>Address:</label>
                            <input type="text" class="form-control" id="editAddress">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary btn-save">Save changes</button>
                </div>
            </div>
        </div>
    </div> 

$(document).ready(function(){    
    $('.edit').click(function(){
            var that = this;
            $(this).find(':radio').prop("checked",true);
            loadData(that);
            $('#checkInModal').modal({                 
            });
    });

    function loadData(that){
        $('#editName').val($(that).parent().find('.name').html());
        $('#editAddress').val($(that).parent().find('.address').html());
    }

    $('.btn-save').click(function(){
        // Update the new values inside the Table
        var row = $('input[name=select]:checked').parent().parent();        
        $(row).find('.name').html( $('#editName').val());
        $(row).find('.address').html( $('#editAddress').val());
        $('#checkInModal').modal('hide');

        //Create an object with the saved values and post it to server


    });
});

Answer №3

When you click on the edit button, you should locate the nearest element in relation to that button. Using jQuery, you can achieve this:

<button type="button" data-toggle="modal" data-target="#myModal"></button>


$('.btn').on('click', function(){
   var $row = $(this).closest('tr');
})

Afterwards, you can iterate through all the cells and extract their contents to populate the modal body section.

var $row = $(this).closest('tr');

var $modalContentArea = $('#myModal .modal-body');

$row.find('td').each(function(){

   var $cell = $(this);

   var cellContents = $cell.text();

   $modalContentArea.append('<input type="text" value="' + cellContents +'"/>');

});

The save button needs to be linked to an ajax request. You will have to create a JSON object from the gathered data. Then, utilize the $get function of jQuery to send the request with the JSON object as the parameter.

$('btn-primary').on('click', function(){

    $.get( "process.php", function( data ) {

        //The ajax callback can update the table with the new values.

    })

});

On the server side, you must receive the JSON object, parse it, store it in a database, and then return the new values back to the ajax callback.

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

Error encountered when utilizing the Omnifaces::Ajax::update() method: NoClassDefFoundError Exception

Trying to execute the sample code from Omnifaces library related to the Ajax::update() method results in a NoClassDefFoundError exception. This issue seems to be related to client-ids or component ids, but I'm unsure how to solve this problem. Here ...

Swapped out image hyperlink for a clickable button

As someone new to javascript, I'm encountering an issue with this code. I want to update my image links when a button is clicked in my code. However, the problem is that my image links are already being updated before I even click the button. Below ar ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

One approach could be utilizing either JavaScript object notation or jQuery code to establish class properties that are also classes in their own

Here is an example of what I currently have: var Class1=function(p1,p2){ //constructor code } Class1.prototype={ method:function(){...}, method:function(){...} } I am looking to make Class2 a part of Class1 so that I can do the following: inst ...

What is the process for sending an Ajax request to transfer the data from a table row column to PHP when clicking on the table row?

In my datatable, the first column of each <tr><td> row contains a numeric value. My goal is to click on a row, extract this value, and pass it to a PHP page to store it in a session. Although I have attempted the code snippet below, it does n ...

Monitoring alterations in dynamically produced input fields using jQuery

My code currently generates multiple input fields dynamically, each related to a specific database record. I utilize PHP's dynamic array notation ('[]') to store the input values. Everything is working smoothly up to this point... Now, I am ...

The appearance of HTML varies depending on the type of mobile device being used

My email template is having display variations on different mobile devices, with the textbox sometimes centered instead of left aligned as intended. Any suggestions on what might be causing this issue and how to resolve it? Desired Display on All Devices ...

The angular event broadcaster controller is currently unavailable

In my app, there is a search box and a list of results. The search box is controlled by SearchCtrl, while the list of results is managed by DocListCtrl. When a user submits a query, SearchCtrl emits an event that DocListCtrl listens for in order to update ...

Why is it important to understand the meaning of variable = [...variable] in Javascript ES6?

I need clarification on the following variable arg assignment arg = [...arg]; Can you explain what this code snippet does? ...

Adding unique parameters to a rails form

As a newcomer to web development, I am facing the following challenge: I have three models in my application: products class Product < ApplicationRecord has_and_belongs_to_many :steps end steps class Step < ApplicationRecord has_and_belongs_ ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

Error encountered: TypeError: Unable to access attributes of null object (attempting to read 'useMemo')

In the development of a public component titled rc-component version0.1.14, I built a platform that allows for the sharing of common React pages amongst various projects. However, upon attempting to utilize this component in my project, I encountered the f ...

Issue with jsPDF rendering Japanese characters when printing

I am having trouble generating a PDF with Japanese characters こんにちは However, when I view the printed PDF, it shows these characters instead: þÿ0S0“0k0a0o A similar issue was raised in a previous query regarding JsPDF not supporting Japa ...

sort by the last element in the array

I have implemented an angular table that is organized by an array. The structure is such that the second level depends on the first level, and the third level depends on the second, and so forth. For instance: A is the parent of B, B is the parent of C. ...

I attempted to upload an image using the Google Drive API, but encountered an error in the response

I am attempting to upload an image using the Google Drive API, but I encountered an error in the response message. The error reads as follows: "Failed to load resource: the server responded with a status of 403 ()" ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

How can you effectively close an automatically opening dialog during AngularJS testing with Protractor in order to proceed with test execution seamlessly?

Currently, I am in the process of developing a series of automated tests for a software product within my company. The software itself is built using AngularJS, and to create the tests, I am utilizing Protractor. My focus right now is on creating tests th ...

Double the names in a single <input>

Is it possible to assign two different names within a single input tag, like this: <input type='text' name='food' name='user_search_input'>? In my PHP file, I intend to use the input in two separate "if" clauses - one fo ...

What is the best way to display a component based on a certain condition?

There are two instances where the Items component needs to be displayed. However, in one instance an additional component, Filters, is required while in another it is not. The Filters component is nested inside Items. When attempting to implement this, ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...