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.
You're pretty close. There are two issues:
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>
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');
}
Try This one It should work for me
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function EditRecord(elem) {
var chg = $(elem).closest('tr').children('td').siblings(':first-child');
chg.find('div:first-child').hide();
chg.find('div:nth-child(2)').show();
}
</script>
</head>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With