JavaScript function table cell used in first line only

I had a JavaScript click function on a table row, but when I click on it, the function only works on the first row. How to fix it?

<script type="text/javascript">
   $(document).ready(function(){  
        $('#detpanel').hide();
        $("#showdet").click(function(){
            $('#detpanel').slideDown(500);
        });
        $("#hidedet").click(function(){
            $('#detpanel').slideUp(500);
        });
        $('#showdet').hover(function(){
            $(this).divhover("background-color", "yellow");
        });
    });    
</script>

<tbody>
   <?php $i = 0; ?>
    @foreach ($auser as $res)
       <?php $i += 1; ?>
           <tr @if($i%2==0) class="bgcolor dihover" @endif id='showdet' class="dihover">
               <td>{{ $res->id }}</td>
               <td>{{ $res->name }}</td>
               <td>{{ $res->email }}</td>
               <td>
                   <a class="default-btn" href="/pms/admin/user/edit/{{ $res->id }}">Edit</a>&nbsp;|&nbsp;
                   <a type="submit" class="default-btn del" data-id="admin-user" href="pms/admin/user/delete/{{ $res->id }}">Delete</a>
               </td>
            </tr>
    @endforeach
</tbody>

      

+3


source to share


1 answer


The element id must be unique as you create elements in the loop using class.

When using the ID selector, it only returns the first element with the specified ID, so in your case, the click handler only becomes registered for the first element

                <tbody>
                    <?php $i = 0; ?>
                    @foreach ($auser as $res)
                        <?php $i += 1; ?>
                        <tr @if($i%2==0) class="bgcolor dihover" @endif class='showdet' class="dihover">
                            <td>{{ $res->id }}</td>
                            <td>{{ $res->name }}</td>
                            <td>{{ $res->email }}</td>
                            <td>
                                <a class="default-btn" href="/pms/admin/user/edit/{{ $res->id }}">Edit</a>&nbsp;|&nbsp;
                                <a type="submit" class="default-btn del" data-id="admin-user" href="pms/admin/user/delete/{{ $res->id }}">Delete</a>
                            </td>
                        </tr>
                    @endforeach
                </tbody>

      



then use a class selector to register a click handler

$(document).ready(function () {
    $('#detpanel').hide();
    $(".showdet").click(function () { //use class selector here
        $('#detpanel').slideDown(500);
    });
    $("#hidedet").click(function () {
        $('#detpanel').slideUp(500);
    });
    $('#showdet').hover(function () {
        $(this).divhover("background-color", "yellow");
    });
});

      

+2


source







All Articles