Manipulating HTML Tables – Part 4 (Editing Rows)

You have learned how to add rows and delete rows from an HTML table in my last 3 blog posts. Now, let’s turn our attention to editing rows in an HTML table. Just like you added a Delete button to each row in your table, you will now add an Edit button as well (Figure 1).

Figure 1: Add an edit button to allow a user to edit a single row in the table

The HTML

The HTML is similar to that shown in my last blog post, with another <th> added to allow for a column where you will place an ‘Edit’ button. I have highlighted the change in bold in the code below.

 

<div class="container">

  <h1 class="text-center">Edit Row in a Table</h1>

  <div class="row">

    <div class="center-block col-sm-6">

      <table id="peopleTable" class="table table-bordered

                 table-condensed table-striped">

        <thead>

          <tr>

            <th>Edit</th>

            <th>First Name</th>

            <th>Last Name</th>

            <th>Email</th>

            <th>Delete</th>

          </tr>

        </thead>

      </table>

    </div>

  </div>

  <div class="row">

    <div class="center-block col-sm-6">

      <div class="panel panel-primary">

        <div class="panel-heading">

          Person Information

        </div>

        <div class="panel-body">

          <div class="form-group">

            <label for="firstname">

              First Name

            </label>

            <input type="text"

                    class="form-control"

                    value="Paul"

                    id="firstname" />

          </div>

          <div class="form-group">

            <label for="lastname">

              Last Name

            </label>

            <input type="text"

                    class="form-control"

                    value="Sheriff"

                    id="lastname" />

          </div>

          <div class="form-group">

            <label for="email">

              Email

            </label>

            <input type="email"

                    class="form-control"

                    value="PSheriff@pdsa.com"

                    id="email" />

          </div>

        </div>

        <div class="panel-footer">

          <div class="row">

            <div class="col-xs-12">

              <button type="button" id="updateButton"

                      class="btn btn-primary"

                      onclick="updatePerson();">

                Add

              </button>

            </div>

          </div>

        </div>

      </div>

    </div>

  </div>

</div>

Creating a Row with an Edit Button

Just like you added a button for deleting a row when you add the user input to the row in the table, you add a button for editing a row as well. This is done exactly the same as what you did for the delete button, but the onclick event calls a different function, of course. In the code highlighted in bold you see the edit button is created. In the onclick for this button you call a function named displayPerson().

function buildPersonTableRow() {

  var ret =

  "<tr>" +

    "<td>" +

      "<button type='button' " +

              "onclick='displayPerson(this);' " +

              "class='btn btn-default'>" +

              "<span class='glyphicon glyphicon-edit' />" +

      "</button>" +

    "</td>" +

    "<td>" + $("#firstname").val() + "</td>" +

    "<td>" + $("#lastname").val() + "</td>" +

    "<td>" + $("#email").val() + "</td>" +

    "<td>" +

      "<button type='button' " +

              "onclick='deletePerson(this);' " +

              "class='btn btn-default'>" +

              "<span class='glyphicon glyphicon-remove' />" +

      "</button>" +

    "</td>" +

  "</tr>"

 

  return ret;

}

Since you need to build the exact same HTML regardless of whether you are adding a new row, or replacing an existing row with new data, this new function called buildPersonTableRow() is created.

Display Data in Input Fields

When the user clicks on the Edit button in the table you need to do a couple of things. First you need to get the current row that is being edited right now and store that for future use. To do this you need to create a variable that is outside of any function within your <script> tags.

<script>

  // Current row being edited

  var currentRow = null;

 

</script>

Next you write the displayPerson() function to calculate the current row by getting the <tr> tag that is the parent for the ‘Edit’ button. You now get the individual <td> columns in an array by selecting all <td> elements from the current row. You use the appropriate columns to retrieve each input field such as first name, last name and email. You use the val() function to update each text box from each column of data. Finally, so we know that we are in ‘Edit’ mode as opposed to ‘Add’ mode, you change the text of the ‘updateButton’ to ‘Update’.

function displayPerson(ctl) {

  currentRow = $(ctl).parents("tr");

  var cols = currentRow.children("td");

 

  $("#firstname").val($(cols[1]).text());

  $("#lastname").val($(cols[2]).text());

  $("#email").val($(cols[3]).text());

 

  // Change Update Button Text

  $("#updateButton").text("Update");

}

Updating the Data

When the user clicks on the updateButton it always calls the updatePerson() function. However, depending on what the text is in the updateButton will determine whether or not we are adding or editing. Remember that when you click on the ‘Edit’ button it changes the text of the update button. So in this function you simply test to see what that text says and perform the appropriate function based on that text.

function updatePerson() {

  if ($("#updateButton").text() == "Update") {

    updatePersonInTable();

  }

  else {

    addPersonToTable();

  }

}

If the Update buttons’ text says ‘Update’, call a method to update a person in the table. There are a couple of ways you can update a person. You already saved the row in the ‘currentRow’ variable, so you could reference each cell individually in that row and update each cell in the table using the val() function of each input field. Another method is to add the changed data to the row immediately after the current row, then delete the current row from the table. I have chosen to use the latter as this allows me to reuse the buildPersonTableRow() function we wrote earlier. Lastly, change the text back to Add on the update button. You could also clear the input fields if you want so the user knows they are back in “Add” mode.

function updatePersonInTable() {

  // Add changed row to table

  $(currentRow).after(buildPersonTableRow());

  // Remove original row

  $(currentRow).remove();

  // Change Update Button Text

  $("#updateButton").text("Add");

}

Summary

In the last 4 blog posts you saw how to add, edit and delete rows using 100% client-side code. With just a little HTML, jQuery and JavaScript you are able to create a nice way for users to add, edit and delete records without making a bunch of round-trips to the web server. This will go a long ways towards making your web pages really fast.

Past Blog Content

Blog Archive

No Comments