Open In App

How to send row data when clicking button using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

To send row data when clicking a button using JavaScript, you can follow a straightforward approach by associating the button with the corresponding row data.

Approach:

  1. HTML Structure:
    • The HTML file contains a table with columns for Name, Email, and an Action button in each row. Each <tr> element has data-name and data-email attributes to store the corresponding row data.
  2. JavaScript Function:
    • The handleButtonClick JavaScript function is defined to handle button clicks. It takes the clicked button as a parameter and retrieves the row data from the associated <tr> using the dataset property.
  3. Button Click Event:
    • The button in each row is assigned an onclick attribute, calling the handleButtonClick function with this as a parameter. This allows the function to access the specific button and its associated row.
  4. Data Retrieval:
    • Inside the handleButtonClick function, the row data (Name and Email) is retrieved using the dataset property of the <tr> element. This enables easy access to the data stored in the data-* attributes.
  5. Data Handling (Simulated):
    • For demonstration purposes, the example simulates sending the retrieved data, displaying a message in the console. In a real-world scenario, you might replace the console.log statement with actual data processing or an AJAX request to send the data to a server

Example: This example shows the above-explained approach.

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Row Data Example</title>
</head>
 
<body>
 
    <table border="1">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr data-name="John Doe" data-email="john@example.com">
                <td>John Doe</td>
                <td>john@example.com</td>
                <td><button onclick="handleButtonClick(this)">Send Data</button></td>
            </tr>
            <!-- Add more rows as needed -->
        </tbody>
    </table>
 
    <script>
        function handleButtonClick(button) {
            // Accessing row data using the data-* attributes
            const name = button.parentNode.parentNode.dataset.name;
            const email = button.parentNode.parentNode.dataset.email;
 
            // Simulate sending data (you can perform an AJAX request here)
            console.log(`Sending data: Name - ${name}, Email - ${email}`);
        }
    </script>
 
</body>
 
</html>


Output:

email



Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads