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:
-
HTML Structure:
-
The HTML file contains a table with columns for Name, Email, and an Action button in each row. Each
<tr>
element hasdata-name
anddata-email
attributes to store the corresponding row data.
-
The HTML file contains a table with columns for Name, Email, and an Action button in each row. Each
-
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 thedataset
property.
-
The
-
Button Click Event:
-
The button in each row is assigned an
onclick
attribute, calling thehandleButtonClick
function withthis
as a parameter. This allows the function to access the specific button and its associated row.
-
The button in each row is assigned an
-
Data Retrieval:
-
Inside the
handleButtonClick
function, the row data (Name and Email) is retrieved using thedataset
property of the<tr>
element. This enables easy access to the data stored in thedata-*
attributes.
-
Inside the
-
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: