How to display hidden table rows with radio buttons using JQuery

吃可爱长大的小学妹 提交于 2019-12-25 01:44:57

问题


I have multiple table rows that has a set of radio buttons on each row (Approve & Reject). When I select Reject I want to display a hidden tr underneath it and I'm using jquery to insert HTML into the tr. When I select Approve the tr should be hidden once again.

I can't get it to work exactly how I explained it, when I toggle between the Approve & Reject radio buttons the hidden tr gets displayed on all the rows. I want it to only show underneath the radio button I clicked on.

My Fiddle: http://jsfiddle.net/4A7TD/

HTML:

<table>
  <tr>
    <td class="left">
        <input type="radio" name="approval1" value="approve" /> APP &nbsp; 
        <input type="radio" name="approval1" value="reject" /> REJ
    </td>
 </tr>
 <tr class="hiddenColumn">

 </tr>
 <tr>
    <td class="left">
        <input type="radio" name="approval2" value="approve" /> APP &nbsp;
        <input type="radio" name="approval2" value="reject" /> REJ
    </td>
 </tr>
 <tr class="hiddenColumn">

 </tr>
</table>

JQuery:

    $('.hiddenColumn').hide();

    $('input[type=radio]').change(function() {
     if ($(this).val() == 'reject') {
       $('.hiddenColumn').show();
       var showColumn = ($(this).closest('tr').next('tr'));
       showColumn.html('<td class="left">*Reason for Rejection<br /><textarea class="width350" name="reasonForRejection"></textarea></td>');
        } else if ($(this).val() == 'approve') {
            ($(this).closest('tr').next('tr')).hide();
       };
   });

回答1:


Instead of change use click event and remove this line $('.hiddenColumn').show() which is the culprit. Just show the next row by calling show method only on that row which you have already found. Also instead of using $(this).val() to get the value, you can just use this.value inside the handler.

   $('input[type=radio]').click(function() {
     var $nextTR = $(this).closest('tr').next('tr');
     if (this.value == 'reject') {
       $nextTR
       .html('<td class="left">*Reason for Rejection<br /><textarea class="width350" name="reasonForRejection"></textarea></td>')
       .show();
     } 
     else if (this.value == 'approve') {
        $nextTR.hide();
     };
   });

Demo



来源:https://stackoverflow.com/questions/9115364/how-to-display-hidden-table-rows-with-radio-buttons-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!