What is the best way to display a form within every row of a data table?

I am currently working on a page that retrieves data from a backend and displays it in a Datatable. One of the columns in my table is an input field with a default value fetched from the backend, and another column contains buttons. How can I implement a function that allows me to access the Oid value of the corresponding row whenever a button in any row is clicked? It's important to note that if I edit the input field, I should be able to access the edited value instead of the default value fetched from the backend.

let page = 1;
var exchange = "all";
var search = "";
var urlPage = "http://127.0.0.1:8000/mw_api/?page=" + page + "&exchange=" + exchange + "&search=" + search;

function loadTable() {
  urlPage = "http://127.0.0.1:8000/mw_api/?page=" + page + "&exchange=" + exchange + "&search=" + search;
  $(document).ready(function() {
    $('#mwdata').DataTable({
      "processing": true,
      "serverSide": true,
      "pageLength": 15,
      "ajax": {
        "data": function(d) {
          var info = $('#mwdata').DataTable().page.info();
          page = info.page + 1;
          search = d.search.value;
          urlPage = "http://127.0.0.1:8000/mw_api/?page=" + page + "&exchange=" + exchange + "&search=" + search;
          console.log(urlPage, page, 'SEARCH', search);
          $('#mwdata').DataTable().ajax.url(urlPage);
          page = info.page + 1;
          console.log(page);
        }
      },
      "columns": [{
          "data": "MarketName"
        },
        {
          "data": "CoinName"
        },
        {
          "data": "MainMarket"
        },
        {
          "data": "MarketType"
        },
        {
          "data": "Exchange"
        },
        {
          "data": "Bid"
        },
        {
          "data": "Oid",
          "render": function(data, type, row) {
            return "<input type='text' class='form-control' value='" + data + "'>";
          }
        },
        {
          "data": null,
          "defaultContent": "<button class='btn btn-primary'>Update</button>"
        }

      ]
    });


  });
}

function setExchange() {
  exchange = document.getElementById("exchanges").value;
  // reload the table
  $('#mwdata').DataTable().ajax.reload();
}

loadTable();
<head>
<script
  src="https://code.jquery.com/jquery-3.7.1.min.js"
  integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
  crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46242929323532342736067368756875">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d0ddddc6c1c6c0d3c2f2879c819c81">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.0.2/css/dataTables.dataTables.css">
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
</head>
<div class="container">

  <table id="mwdata" class="display" style="width:100%">
    <thead>
      <tr>
        <th>Market Name</th>
        <th>Coin Name</th>
        <th>Main Market</th>
        <th>Market Type</th>
        <th>Exchange</th>
        <th>Bid Price</th>
        <th>OID</th>
        <th>Update</th>
      </tr>
    </thead>
  </table>
</div>

Answer №1

If you want to access data in a table, you can utilize the .cell(row, column) function from the datatable plugin. However, my preference is to interact with the DOM directly when dealing with tables. Yes, that's correct.

document.querySelector('table').querySelectorAll(".btn").forEach(function(btn) {
  btn.addEventListener('click', function(ev) {
    var row = this.closest('tr');
    var tds = row.querySelectorAll(":scope>td")
    var td = tds[0] // 0 is first column
    var input = td.querySelector("input")
    var value = input.value
    alert(value)

  })
})
table {
  border-collapse: collapse;
  text-align: left;
}
<table border="1">
  <thead>
    <tr>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value="Joe Biden"></td>
      <td><button class="btn">Get Value</button></td>
    </tr>
    <tr>
      <td><input type="text" value="Jane Doe"></td>
      <td><button class="btn">Get Value</button></td>
    </tr>
  </tbody>
</table>

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

Struggling with sending form data to the back end when uploading images in Angular

I've been facing a challenge trying to implement profile picture upload alongside standard text data and sending it all to the backend to create a new user through mongoose. Despite my efforts, using tools like ng-file-upload/angular-file-upload and e ...

Angular ui router - Transitioning from one state to the same state, when no parameters are provided, results in

Check out the Plunker Demo <script> var myapp = angular.module('myapp', ["ui.router"]) myapp.config(function($stateProvider, $urlRouterProvider) { // If there is no matching URL, go to /dashboard $urlRouterProvider. ...

"Dynamic" visual in a Vue.js development scheme

Utilizing Vue.js for the development of a hybrid mobile application has been my current focus, with the Quasar framework serving as a key component. Recently, I incorporated an image into the application using the <img /> tag and utilized the followi ...

Creating dynamic captions in an Angular grid is an essential feature for enhancing the

Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

Trouble with the drop-down menu displaying "string:2" in an AngularJS application

Currently, I am utilizing AngularJS ng-model to choose the value from a drop-down menu. Additionally, I am implementing datatable for organizing the columns. <select id="{{user.id}}" ng-model="user.commit" name="options" ng-change="update_commit_level ...

Handling 404 Response from WebAPI in $Http.get() Function

While using my web application, I am executing a GET command to access a remote HTTP WebAPI service. $http.get(url).then(function(data) { do_something(); }); When the WebAPI successfully returns data, everything functions as expected. However, in cases w ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...

Implementing a tooltip or bubble display functionality without using the span tag or title attribute

Is there a way to display tooltips when users hover over specific text or keywords? The text is retrieved directly from the database, so adding span or div tags or title information is not an option. Are there any methods to automatically generate tooltips ...

What steps should be taken to trigger an API call once 3 characters have been entered into a field

In my current project, I am dealing with a parent and child component setup. The child component includes an input field that will emit the user-entered value to the parent component using the following syntax: <parent-component (sendInputValue)="g ...

How can I enable the "edit" function for a button within a list item?

I am currently working on a feature that allows users to edit list rows by clicking a button. However, I am facing an issue where the "edit" button only edits the first row instead of the matched line. This functionality is part of a program I am developi ...

Struggling to interpret the array of objects retrieved from a call to UrlFetchApp.fetch in Google App Script

When UrlFetchApp.fetch is called, it provides an array of objects that are stored in the variable 'results': var results = [{"Category 1": "Benefits/Compensatio", "Category 2": "Compensation", "Category 3": "Recognizing You", "Processing Team": ...

The background gently fades away, directing all attention to the popup form/element

After extensive searching, I have yet to find a straightforward solution that seems to be a standard practice on the web. My goal is to create a form that appears in the center of the screen when a button is clicked using CSS or jQuery. I would like the ...

Tips for saving JSON information into a variable using JavaScript

I am in need of a function called ** getJson () ** that can fetch and return data from a json file. Here is the JSON data (file.json): [ { "01/01/2021":"Confraternização Universal", "1 ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

Retrieving width and height of the content block inner in Framework7, excluding navbar and toolbar dimensions

Is there a reliable way to determine the width and height of the page content-block-inner, excluding the navbar and toolbar? This measurement can vary across different devices and operating systems. I attempted to assign an id to the content-block-inner a ...

Is there a way to adjust the size of text to perfectly fit within a fixed size div?

I find this scenario quite common, but I haven't come across any solutions for it: Let's say there is a fixed-width div that displays dynamically changing numbers. How can we adjust the font size so that larger numbers fit well within the fixed ...

Numerous intersecting lines on display within Google Maps

Currently, I am working on displaying multiple flight routes on Google Maps. I have implemented polylines with geodesic to achieve this functionality successfully. However, a challenge arises when more than two flights intersect the same route, causing o ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

Instructions on converting a SQL expression to Sequelize

Could someone assist with converting this to sequelize? CREATE TABLE "fundraiserUpdates" ( "updateId" SERIAL, "updateFundraiserId" INTEGER NOT NULL, "updateTitle" TEXT NOT NULL, "updateDescription" TEXT NOT NULL, CONSTRAINT "pk_fundraiser ...