Updating a specific row in a multiple row form can be achieved when the input field names match in a column

My task involves working with a report that generates a form in input mode. This form contains multiple rows of data, each row consisting of a button and an input field. The input field name remains consistent across all rows for easier processing by the CGI program. I am looking to implement a functionality where clicking on the button within a specific row automatically updates the input field on that same row using JavaScript. How can JavaScript locate and update the correct input field based on the button clicked?

I find myself at a standstill right from the beginning and unsure of how to proceed.

Here is a simplified version of the HTML structure:

<table>
<tr>
<td>Frank</td>
<td>Burns</td>
<td><input type="text" name="overtime" value="1000"></td>
<td><input type="button" name="averageIN" value="Average In" onclick="return avgIN('1000,'2000');">
</tr><tr>
<td>John</td>
<td>Doe</td>
<td><input type="text" name="overtime" value="500"></td>
<td><input type="button" name="averageIN" value="Average In" onclick="return avgIN('500,'2000');">
</tr>
</table>

Below is the incomplete snippet of the JavaScript code:

function avgIN(orig, avg) {

    let text = "Request to Average In Overtime:\n\n"+
       "Current OT Total: "+orig+"\n"+
       "Averaged In Total: "+avg+"\n\n"+
       "Click OK to accept";
    if (confirm(text) == true) {
        // Add logic here to update the overtime input field on the same row with the value of "avg"
        }
    else {
        alert("Average In function canceled");
        }
    }

Answer №1

Implement event delegation...

with this approach:

const myTable = document.querySelector('#my-table')

myTable.onclick = e =>
  {
  if (!e.target.matches('button[data-avg-in]')) return // exit
  
  let 
    [orig, avg] = e.target.dataset.avgIn.split(',').map(Number)
  , txt =
`Request to Average In Overtime:

Current OT Total: ${orig} 
Averaged In Total: ${avg}

Click OK to accept`
       ;
  if (confirm(txt)) 
    {
    e.target.closest('tr').querySelector('input[name="overtime[]"]').value = 'avg'
    } 
  else 
    {
    alert('Average In function canceled');
    }
  }
<table id="my-table">
  <tr>
    <td>Frank</td>
    <td>Burns</td>
    <td><input type="text" name="overtime[]" value="1000"></td>
    <td><button data-avg-in="1000,2000" >Average In</button></td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td><input type="text" name="overtime[]" value="500"></td>
    <td><button data-avg-in="500,2000" >Average In</button></td>
  </tr>
</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

Chrome extension causing delays in rendering HTML on webpage

Currently, I am developing a script (extension) that targets a specific HTML tag and performs certain actions on it. The challenge I am facing is that this particular HTML tag gets dynamically loaded onto the page at a certain point in time, and I need to ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Node.js: Understanding the issue of a mysterious null value in JSON responses sent to clients

As a beginner in the world of Node.js and JavaScript, I have been struggling to find a solution to my problem even after extensive searching. My current challenge involves sending a JSON object to a Node.js server with an array of 2 elements (longitude an ...

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...

How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven&a ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

The JavaScript function on the specified /url page is not functioning properly following the execution of history.push(/url) on click

I have a JavaScript function that toggles the display of login password. However, when I redirect to the login page from another page using history.push(/login), the function does not work. It does work when I use (/login) in the href tag. How can I resolv ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

add text nodes with unnecessary quotation marks around my selection list

Looking to incorporate a select list into my website using a button. I must utilize nodes for access within the DOM to retrieve its value later, so innerHTML isn't an option. Experiencing difficulty as createTextNode seems to encase my list in quota ...

Is there a way to make FullPage and Lightbox compatible with each other?

Currently utilizing Fullpage.js for my website, I am looking to incorporate a lightbox in one of the sections. However, upon attempting to load the script and CSS, my fullpage layout breaks and the sections collapse. I have experimented with placing the ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...

When should we utilize the React.Children API in React applications?

Exploring the potential use cases of the React.Children API. The documentation is a bit confusing for me (Using React v.15.2.0). https://facebook.github.io/react/docs/top-level-api.html#react.children According to the documentation, this.props.children ...

Unable to locate the TabBar Review Icon while on the Settings screen

Every time I navigate to the settings screen, the Review Icon (favorite) disappears. However, it reappears when I go back to the Review screen. Can anyone explain why this is happening? Here is a screenshot I captured along with a snippet of code from my p ...

Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue: The expected output should resemble: [ {first:"John", last: "Smith", id: ...

Initiate an Elementor popup upon form submission (After submit event) using Contact Form 7 in WordPress

I have incorporated Elementor popups and contact form 7 into my WordPress website. Currently, my goal is to activate the Elementor popup after the contact form 7 form has been submitted. Below is what I have tried so far, and there have been no console er ...

Send an AJAX request to the server without waiting for a response using a JavaScript variable

My click counter is not sending variables to the server. I have tried finding examples on how to do this, but no matter what I attempt, the data is not being sent to the server. It seems like using AJAX would be the best option, but I must be doing someth ...

Is it necessary to dispose of node.js domains? When is the appropriate time to do so?

In my Express application, I utilize domains for each incoming request. To ensure that all subsequent middlewares are executed within a domain, I've implemented a middleware. app.use(function(req, res, next) { var d = domain.create(); d.req ...