How to send row data when clicking button using JavaScript ?
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 has data-name
and data-email
attributes to store the corresponding row data.
- 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.
- 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.
- 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.
- 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 >
</ 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:
Last Updated :
15 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...