Darkloki
Darkloki

Reputation: 686

JQuery select cells in row and change attribute?

I have a table with a link in one of the cells. I would like to change the "contenteditable" attribute to "true" (if it exist, not the last 2 cells for example) for each cell in the same row when you click the "edit" link for that row. I believe I am close thanx to other articles here on SO. Any suggestions? Thank you muchly in advance.

function edit_me(e) {
        $.each(this.cells, function () {
            $(this).attr("contenteditable", "true");
        });
    }
<table border="0" cellpadding="7">
    <tr>
    <th>col 1 </th>
    <th>col 2 </th>
    <th>col 3 </th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
    </tr>
    <tr>
    <td contenteditable="false">1</td>
    <td contenteditable="false">2</td>
    <td contenteditable="false">3</td>
    <td><a href="#" onclick="edit_me(this)">edit</a></td>
    <td>delete</td>
    </tr>
     <tr>
    <td contenteditable="false">1</td>
    <td contenteditable="false">2</td>
    <td contenteditable="false">3</td>
    <td><a href="#" onclick="edit_me(this)">edit</a></td>
    <td>delete</td>
  </tr>
</table>

Upvotes: 1

Views: 458

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

  1. Make e a jQuery object by wrapping in $()
  2. Use find() to get the children with attribute contenteditable

function edit_me(e) {

    $.each($(e).closest('tr').find('[contenteditable]'), function() {
      $(this).attr("contenteditable", "true");
    });
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table border="0" cellpadding="7">
  <tr>
    <th>col 1</th>
    <th>col 2</th>
    <th>col 3</th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
  </tr>
  <tr>
    <td contenteditable="false">1</td>
    <td contenteditable="false">2</td>
    <td contenteditable="false">3</td>
    <td><a href="#" onclick="edit_me(this)">edit</a>
    </td>
    <td>delete</td>
  </tr>
  <tr>
    <td contenteditable="false">1</td>
    <td contenteditable="false">2</td>
    <td contenteditable="false">3</td>
    <td><a href="#" onclick="edit_me(this)">edit</a>
    </td>
    <td>delete</td>
  </tr>
</table>

Update

There is no need for $.each, you can simply do

function edit_me(e) {
  $(e).find('[contenteditable]').attr("contenteditable", "true");
}

Upvotes: 2

jamesblacklock
jamesblacklock

Reputation: 859

Change these:

onclick="edit_me(event)"

And try this:

function edit_me(e)
{
    $(e.target).closest('tr').children('td').attr("contenteditable", "true");
}

Upvotes: 0

Related Questions