How to transfer data from table row to form when button is clicked in JavaScript?

Last Updated on Feb 26, 2024

transfering of table row to form when edit button is clicked.

Consider the following scenario:

You have a page that has a table and a hidden form that will pop up when the edit button is clicked in the action column of your table. When the form shows up, you want the form inputs to have the values of the table row in which the edit button is clicked.

How will you do it?

In this tutorial, I will show you how.

  1. Use data-* attribute in HTML

    The data-* attribute allows us to create our own HTML attribute. We can use it to store data and then access it in our JavaScript.

    To use the data-* attribute, just append the 'data-' at the beginning of your chosen attribute name. For example, if you want to have an 'age' attribute, then you will use 'data-age'.

    In the tr element, create the data-* attribute for all your inputs that you will need to transfer to the form. Then, add the data-edit-button attribute to your edit button; we will use this to select all the edit buttons.

    <tr data-firstname="Jane" data-lastname="Doe">
      <th scope="row">1</th>
      <td>Jane Doe</td>
      <td>
        <button data-edit-button>Edit</button>
      </td>
    </tr>
    
  2. Make it work in JavaScript

    To get the data-* attribute in javascript, just use dataset.property with property as the attribute name that you use in your HTML.

    For example, if you use the data-age attribute in your HTML, then you will use dataset.age in your javascript.

    In addition, if you use an attribute name that is more than one word separated by dashes, then it will become camelCase. For example, if you use data-phone-number in your HTML, then you will use dataset.phoneNumber in your JavaScript.

    //select all the edit buttons
    const editButtons = document.querySelectorAll('[data-edit-button]');
    
    //select each edit button and add click listener 
    for (const editButton of editButtons) {
      editButton.addEventListener('click', setEditForm);
    }
    
    function setEditForm(e) {
      //get the input element in the form
      const lastnameInput = document.getElementById('lastname-input');
      const firstnameInput = document.getElementById('firstname-input');
    	
      //using parentNode property twice, 
      //we can get to the tr element from the edit button
      lastnameInput.value = e.target.parentNode.parentNode.dataset.lastname;
      firstnameInput.value = e.target.parentNode.parentNode.dataset.firstname;
    }
    

Conclusion

To transfer data from a table row to a form, we can use the data-* attribute in HTML to store it and use it in JavaScript using dataset.property.

In our JavaScript, first we select all the edit buttons and then add the function setEditForm() as its click listener. In that function, we select the form inputs and then set their value.

© John Michael Balbarona