Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
SpiderCode Avatar asked Oct 21 '25 13:10

SpiderCode


2 Answers

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');
}
like image 112
T.J. Crowder Avatar answered Oct 23 '25 02:10

T.J. Crowder


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>
like image 30
jai lalawat Avatar answered Oct 23 '25 03:10

jai lalawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!