简体   繁体   中英

Put specific tds from a table row into edit using jQuery (then update w/ ajax)

I'm somewhat new to jQuery, so I could use some help here.

This is my issue:

I have a PHP script outputting a dynamic table. Each row has an "edit" button, plus some other fields. Only 3 of those need to be turned into an input box. The edit button should only put that specific row into "edit mode." I got as far as assigning each row a unique class by adding a number to the end of it.

I have been able to use jQuery to change all of the rows into edit mode, but I need it to be specific to a row.

An example row would have classes like name0, price0, and desc0. The next row would go on to classes name1, price1, and desc1 (for the fields that need changed). How can I reference these values and pass them to jQuery so it processes an event on just those elements?

There are two ways of doing this:

  1. Dynamically creating the elements when the button is pressed; or

  2. Hiding and showing elements that already exist.

Too much DOM manipulation can be really slow (particularly on certain browsers) so I favour (2). So for example:

<table class="editable">
<tbody>
<tr>
  <td>one</td>
  <td>
    <div class="view">two</div>
    <div class="edit"><input type="text"></div>
  </td>
  <td>
    <div class="view">three</div>
    <div class="edit"><input type="text"></div>
  </td>
  <td>
    <input type="button" class="edit" value="Edit">
    <input type="button" class="send" value="Send" disabled>
    <input type="button" class="cancel" value="Cancel" disabled>
  </td>
</tr>
</tbody>
</table>

with:

table.editable div.edit { display: none; }

and

$(function() {
  $(":button.edit").click(function() {
    var row = $(this).closest("tr");
    row.find("input.view").attr("disabled", true");
    row.find("div.view").each(function() {
      // seed input's value
      $(this).next("div.edit").children("input").val($(this).text());
    }).fadeOut(function() { // fade out view
      row.find("div.edit").fadeIn(function() { // fade in edit
        row.find("input.edit").removeAttr("disabled"); // enable edit controls
      });
    });
  });
  $(":button.cancel").click(function() {
    var row = $(this).closest("tr");
    row.find("input.edit").attr("disabled", true");
    row.find("div.edit").fadeOut(function() {
      row.find("div.view").fadeIn(function() {
        row.find("input.view").removeAttr("disabled");
      });
    });
  });
  $(":button.save").click(function() {
    // ...
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM