Input the latest data into the Bootstrap form

Implementing the bootstrap4 framework in my web application, I have a table displaying various values. Each row includes an edit button at the end of the row (last column). The requirement is that when this edit button is clicked, a form should pop up with the existing data from that specific row, allowing the user to modify only the necessary fields. While I understand that JavaScript is needed to fill the text boxes within the form, I am unsure of the correct method to achieve this using the bootstrap4 framework.


      <div class="table-responsive">
          <table class="table table-hover table-dark">
            <thead>
              <tr>
                <th scope="col">Channel No</th>
                <th scope="col">Channel Name</th>
                <th scope="col">Description</th>
                <th scope="col">Recording Status</th>
                <th scope="col">Edit</th>
              </tr>
            </thead>
            <tbody>
              ...
            </tbody>
          </table> 
      
    

This is the edit button


      <button type="button" class="btn btn-info" data-toggle="modal" data-target="#ModalLoginForm" >
        Edit
      </button>
    
  

This is the POP form(modal) for the edit button


      <div id="ModalLoginForm" class="modal fade">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  ...
              </div><!-- /.modal-content -->
          </div><!-- /.modal-dialog -->
      </div><!-- /.modal -->
    
  

Answer №1

Presented below is a fully functional sample code, offering an enhanced and more dynamic solution tailored to your requirements. This code snippet demonstrates how you can leverage the native bootstrap jQuery function to display your modal when the "edit" button in your row is clicked.

You have the ability to monitor which button triggered the modal, enabling you to retrieve all relevant data using jQuery functions such as closest() and find()

Upon obtaining the necessary data from the respective row, you can then populate it into the input fields within the modal.

Furthermore, an additional feature has been incorporated where if the recording status is set to Y, the checkbox in the modal will be automatically checked; conversely, if it's set to N, the checkbox will remain unchecked.

Experience the Live Working Demo:

$("#ModalLoginForm").on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) //Button that triggered the modal

  // Extracting data
  var cId = button.closest('tr').find('th').text() //1st th
  var cName = button.closest('tr').find('th').next().text() //2nd th
  var cDesc = button.closest('tr').find('th').next().next().text() //3 th
  var isRecord = button.closest('tr').find('th').next().next().next().text() //4 th

  // Applying the retrieved data
  $('[name="channelid"]').val(cId);
  $('[name="channel"]').val(cName);
  $('[name="description"]').val(cDesc);

  // Checking the checkbox status
  if (isRecord == 'Y') {
    $('[name="remember"]').prop('checked', true);
  } else {
    $('[name="remember"]').prop('checked', false);
  }
})
<!-- Incorporating the Latest Compiled and Minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Importing the jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS Integration -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Utilizing the Latest Compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="table-responsive">
  <table class="table table-hover table-dark">
    <thead>
      <tr>
        <th scope="col">Channel No</th>
        <th scope="col">Channel Name</th>
        <th scope="col">Description</th>
        <th scope="col">Recording Status</th>
        <th scope="col">Edit</th>
      </tr>
    </thead>
    <tbody>
      <!-- Table entries with 'Edit' button -->
    </tbody>
  </table>
  <div id="ModalLoginForm" class="modal fade">
    <div class="modal-dialog" role="document">
      <div class="modal-content">

        <div class="modal-body">
          <form role="form" method="POST" action="">
            <!-- Form Inputs for Channel Information -->
          </form>
        </div>
      </div>
      <!-- Ending the Modal Content Section -->
    </div>
    <!-- Closing the Modal Dialog Box -->
  </div>
  <!-- End of Modal Section-->

Answer №2

$(".table .btn-info").on("click", function(){ //applying to every .btn-info in every .table, consider creating a new class or id for your table
    var thContentFromClickedRow = $(this).closest("tr").find("th").html(); // copying data from the TH in the same ROW as the clicked button

    $('[name="channelid"]').val(thContentFromClickedRow); //selecting desired input by name and using .val to insert data
});

This code demonstrates how to easily retrieve inner HTML from a specific column in the same row where the button is clicked. For more in-depth knowledge, consider studying JavaScript/jQuery basics on platforms like W3Schools. This example uses jQuery due to the presence of Bootstrap.

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

JavaScript: inscribe in a specific cell

I have a table cell within a div element and I am trying to display the date for the last Thursday in it: <body> <div> <table id="TableName" width="auto"> <thead> <tr> ... ...

What could be causing the data-price values of my alternative select options to not add up correctly when running this function?

ISSUE I am facing a challenge in calculating the total values of select inputs based on the radio button selected initially. Each radio button corresponds to different select inputs with their own data-price values. Once a radio button is chosen, the div ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

The CSS :lang() selector targets elements within documents that do not specify a particular language

Can elements that do not have a language set or inherited, meaning they are in an unspecified ("unknown") language, be targeted? Facts The language of an HTML document or element can be specified using the HTML lang attribute, for example: <html lang=& ...

"The incredible power of the spread operator in conjunction with EsLint

Is there a way to duplicate an object and modify one of its properties? Here's an example: const initialState = { showTagPanel: false, }; export default function reducerFoo(state = initialState, action) { switch(action.type) { case types.SH ...

An error occurs when using e.slice function

I am facing an issue with my kendoDropDownList that uses kendo UI and jQuery. I cannot figure out why this error is occurring. $("#drpState").kendoDropDownList({ optionLabel: "States...", delay: 10, ...

Is it possible to automatically access the most recent Beta build through package.json and npm?

We are currently working on a project that has a specific dependency requirement for the latest beta build from an npm library. However, there are also -dev builds within the library. For instance, in the "x-library" there might be versions like: "1.2.3- ...

Glitch Uncovered in Excel Spreadsheet I Exported

I have a situation where I am working with an HTML table that includes both text and radio buttons. The issue arises when I attempt to export the table data along with the selected radio button values to Excel using the 'Export to Excel' button. ...

Switch between various components using multiple buttons in Next.js

I am in the process of creating a component that will display different components depending on which button the user selects. Here are the available “pages”: ` const navigation = [ { name: "EOQ", return: "<EOQgraph />" }, { nam ...

Identifying browser compatibility for date input type with Angular 2 and above

Is there a reliable method to check if the browser supports <input type="date"> in Angular2+? I came across a suggestion on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date where they recommend creating the input element and chec ...

What is the best way to arrange cards in a horizontal stack for easy carousel viewing later on

My main objective is to design a unique card carousel where users can navigate through the cards by clicking on arrows placed on the left and right sides. The approach I am considering involves stacking multiple card-decks and smoothly transitioning to th ...

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

Discovering a value that aligns with one of the values in an array using Javascript

Just a heads up: this quiz is super simple and only has one input field for each question. This block of Javascript code is used to check if the answer entered in the input field is correct or not. In this case, it checks if the answer entered is 'en ...

Leveraging Handlebars Object within JavaScript

Is there a way to pass an entire object into javascript directly? I've tried using the {{{data}}} and {{data}} methods as suggested in other posts, but it doesn't seem to be working for me. Here's what I have in my handlebars file: <scri ...

Ways to create a URL path that is not case-sensitive in NextJs using JavaScript

I am currently working on a project using NextJs and I have encountered an issue with URL case sensitivity. The paths fetched from an API all start with a capital letter, causing inconsistency in the URLs. For instance, www.mysite.com/About. I would like t ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

html table displaying incorrect data while using dynamic data in vue 3

example status 1 Hello there! I'm trying to create a table (check out example status 1 for guidance). Here's the code snippet I am using: <table> <tr> <th>Product</th> <th>Price</th> <th>Av ...

Html5 declares that the statuses of values are not defined

In a chrome extension, I am encountering an issue with the following code: var DB = openDatabase('CMPDB', '1.0', 'Database for CMP', 4 * 1024 * 1024); LoadFromDB(); function LoadFromDB() { DB.transaction( function(t ...

Creating a React table with customizable columns and rows using JSON data sources

My query is this: What is the most effective way to dynamically display header names along with their respective rows? Currently, I am employing a basic react table for this purpose. As indicated in the table (2017-8, 2017-9, ....), I have manually entere ...