简体   繁体   中英

Show a row's information into a right side div by clicking a table's row using jquery

For my recent project, I need to show data in a table. When I click on any row of the table, all the contents of the row will be shown in an additional div. See the code below:

<div class="left-side">
    <table id="data">
        <tr>
            <td>cell(1,1)</td>
            <td>cell(1,2)</td>
            <td>cell(1,3)</td>
        </tr>

        <tr>
            <td>cell(2,1)</td>
            <td>cell(2,2)</td>
            <td>cell(2,3)</td>
        </tr>

        <tr>
            <td>cell(3,1)</td>
            <td>cell(3,2)</td>
            <td>cell(3,3)</td>
        </tr>
    </table>
</div>

<div class="right-side">
    <!-- when a row is clicked, then the respective information is shown here-->
    <!-- for example, if i click the first row, then it shows cell(1,1) and cell(1,2) and cell(1,3) and so on-->
</div>

Please suggest any idea of how to do it using jQuery or JavaScript.

 var string = ''; $("#data tr").click(function() { $(this).find("td").each(function(index) { string += $(this).text(); }); document.write("<br/>" + string); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="left-side"> <table id="data"> <tr> <td>cell(1,1)</td> <td>cell(1,2)</td> <td>cell(1,3)</td> </tr> <tr> <td>cell(2,1)</td> <td>cell(2,2)</td> <td>cell(2,3)</td> </tr> <tr> <td>cell(3,1)</td> <td>cell(3,2)</td> <td>cell(3,3)</td> </tr> </table> </div> <div class="right-side"></div> 

Add a click event handler to your jQuery code:

<script type="text/javascript">
    $(function() {
        $("#data tr").click(function() { //Click event handler for the table column
            var columnText = $(this).text(); //text from the column clicked.
            $(".right-side").text(columnText); //Populates the .right-side div with the text.
        });
    });
</script>

Tip: If you know jQuery, then prefer jQuery over plain JavaScript. It'll lead to a much cleaner and concise code.

Just add a click function to your eg:

function showInrightDif(this) 
{
    var divtext=''
    $(this).find('td').each(function() {
       divtext = divtext + $(this).text;
    });
    $('.right-side').text(divtext);
}

add this code :

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    $('#data tr').click(function () {
        $('.right-side').text($(this).text());
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM