How to Switch Between Table Values

Asked

Viewed 75 times

1

Code

<table border="1px" width="33%">

 <th bgcolor="silver">Trocar de Posição</th>

 <tr>

  <td id="cel_01">Texto 1</td>

 </tr>

 <tr>

  <td id="cel_02">Texto 2</td>

 </tr>

</table>

Example

Before

Text 1

Text 2

Afterward

Text 2

Text 1

By clicking on the Button "Barter", Alternate Line Text 1 for Text 2 and vice versa.

  • 1

    You want to change with the cell that’s on top, underneath, or sort them all one way and be able to reverse that order?

1 answer

2


It does what you wish:

Using Jquery

            $("button").click(function(){
                var text_01 = $("#cell-01").html();
                var text_02 = $("#cell-02").html();

                $("#cell-01").html(text_02);
                $("#cell-02").html(text_01);
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1px">
            <tbody>
                <tr>
                    <td id="cell-01">A Text 1</td>
                </tr>
                <tr>
                    <td id="cell-02">B Text 2</td>
                </tr>
            </tbody>
        </table>
        <br>
        <button>Change</button>

Puro Javascript

            function changeHTML(){
                var text_01 = document.getElementById('cell-01').innerHTML;
                var text_02 = document.getElementById('cell-02').innerHTML;


                document.getElementById('cell-01').innerHTML = text_02;
                document.getElementById('cell-02').innerHTML = text_01;
            };
        <table border="1px">
            <tbody>
                <tr>
                    <td id="cell-01">A Text 1</td>
                </tr>
                <tr>
                    <td id="cell-02">B Text 2</td>
                </tr>
            </tbody>
        </table>
        <br>
        <button onclick="changeHTML()">Change</button>

  • I added the same logic with puto JS ;) I hope I helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.