SpiderCode SpiderCode - 18 days ago 7
HTML Question

JQuery : Get div defined in same table row

I have an HTML table created dynamically using an MVC application and the output of the table is as shown below:

In the

onclick
event of the edit button I want to show
divText
and hide
divLabel
of the same row using jQuery.

I have tried to get
divLabel
as shown below:



function EditRecord(elem) {
var divlabel = $(elem).closest('tr').children('td div#divLabel');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div id="divLabel">
value 1
</div>
<div id="divText" style="display: none">
<input type="text" value="value 1" />
</div>
</td>
<td>
<input type="button" value="edit" onclick="EditRecord(this);" />
</td>
</tr>
<tr>
<td>
<div id="divLabel">
value 2
</div>
<div id="divText" style="display: none">
<input type="text" value="value 1" />
</div>
</td>
<td>
<input type="button" value="edit" onclick="EditRecord(this);" />
</td>
</tr>
</table>





But it is not working for me.

Answer

You're pretty close. There are two issues:

  1. Your HTML is invalid. You cannot reuse the same id for multiple elements. You can use a class instead:

    <tr>
        <td>
            <!-- Note 'class' rather than 'id' below -->
            <div class="divLabel">
                value 1
            </div>
            <!-- Note 'class' rather than 'id' below -->
            <div class="divText" style="display: none">
                <input type="text" value="value 1" />
            </div>
        </td>
        <td>
            <input type="button" value="edit" onclick="EditRecord(this);" />
        </td>
    </tr>
    
  2. closest is right, but children isn't. You want find instead, because the div isn't an immediate child of the row.

So assuming you change your HTML as per #1, we'd use find with a class selector for #2:

function EditRecord(elem) {
    var divlabel = $(elem).closest('tr').find('div.divLabel');
}
Comments