简体   繁体   中英

Swap table cells between rows based on clicking position

I am creating a table of two rows which each consist of 0s and 1s. I have created a function which allows the user to click onto two table cells and a button which swaps the two selected table cells.

I want to be able to swap the td elements from position 0 of a row to the table cell that is selected, and the same for the second row so that multiple table cells are swapped between two rows.

for example, if I select the sixth table cell in both rows, it should swap all the table cells from the beginning of the row to the sixth table cell

I have featured below the code which uses jQuery. Any help will be greatly appreciated:

<html>
<style>

body{
font-size: 30px;
text-align: center;
background-color: ivory;
}
table{
width:100px;

}
h1{
font-family: Helvetica;
font-size: 30px;
}
th{
border: 10px solid black;
padding: 5px;
font-size: 70px;
}
td{
border: 10px solid black;
padding: 5px;
font-size: 130px;

}

tr.center, td.center{
text-align: center;
}
td:not(.notSelectable) {
cursor: pointer
}

td.selected,
td.lastSelected {
background-color: yellow;
color: white;
}
</style>

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("table td:not(.notSelectable)").click(function() {
$(".lastSelected").removeClass("lastSelected");
$(".selected").toggleClass("selected lastSelected");
$(this).addClass("selected");
});
});

function swap() {

if ($(".selected, .lastSelected").length != 2) { return;  }


$("#lblSelectedDate").text($(".selected").siblings(".date").text());
    $("#lblLastSelectedDate").text($(".lastSelected").siblings(".date").text());

  // Set label with value data

   $("#lblSelectedValue").text($(".selected").children("input[type=hidden]").val());
       $("#lblLastSelectedValue").text($(".lastSelected").children("input[type=hidden]").val());

// Swap cell data
var temp = $(".lastSelected").html();
$(".lastSelected").html($(".selected").html());
$(".selected").html(temp);
$(".selected, .lastSelected").removeClass();
}
</script>

<body>
<button onclick="swap();">Crossover</button>
<br /><br />


<table border="1" align = "center">

<tbody>
<tr>

  <td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
  <td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
  <th>P1</th>

</tr>
<tr>

  <td bgcolor ="#ff0000">0<input type="hidden" value="0" /></td>
  <td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
  <td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
  <td bgcolor= "#ff0000">1<input type="hidden" value="1" /></td>
  <td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
  <td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
  <td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
  <td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
  <td bgcolor= "#ff0000">1<input type="hidden" value="1" /></td>
  <td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
  <th>P2</th>
</tr>

</tbody>
</table>

</body>
</html>

I tried to figure out what you need, If I am correct you want to swap td with content between 2 rows with same index, but it should swap all the tds starting from zero index till the selected td index among 2 rows.

If my above statement is correct, you must have requirement to select same td index in both rows, other wise uneven index selection will generate abnormality.

Check my complete working code here:
https://github.com/helloritesh000/swap-table-cells-between-rows-based-on-clicking-position


Comment if required.

<pre>
    <script>
$(function() {
    $("table td:not(.notSelectable)").click(function() {
        var otherTrIndex = ($(this).closest('tr').index() == 1) ? 0 : 1;
        if($(this).closest('tr').find('td.selected').length >= 1 
        || $(this).closest('tr').find('td.lastSelected').length >= 1 
        || ($('td.selected').length > 0 
            && $($('table').find('tr')[otherTrIndex]).find('td.selected').length != ($(this).index() + 1)
                )
        )
        {
            return false;
        }
        $(".lastSelected").removeClass("lastSelected");
        $(".selected").toggleClass("selected lastSelected");
        for(i = 0; i <= $(this).index(); i++)
        {
            $($(this).closest('tr').find('td')[i]).addClass("selected");
        }
    });
});

function swap() {
    var selectedTd = $('td.selected');
    var lastSelectedTd = $('td.lastSelected');
    for(i = 0; i < selectedTd.length; i++)
    {
        var selectedTdHtml = selectedTd[i].outerHTML;
        selectedTd[i].outerHTML = lastSelectedTd[i].outerHTML;
        lastSelectedTd[i].outerHTML = selectedTdHtml;
    }

    $(".selected, .lastSelected").removeClass();
}
</script>

</pre>

The following demo will swap with the counterpart of the .selected cell (from either row -- bidirectionally). Details are commented in demo.

 // Counter let id = 0; // Click on any cell... $('table td').on('click', function() { // Increment counter let idx = id++; // Get index of clicked cell let i = $(this).index(); /* Add/remove .selected to/from clicked cell and... ...add data-id attribute to it with the value of counter */ $(this).toggleClass('selected').data('id', idx); // Find the clicked cell's counterpart let otherCell = $(this).closest('tr').siblings('tr').find('td').eq(i); // Give it the class .marked+counter otherCell.addClass(`marked${idx}`); }); // When button is clicked... $('button').on('click', function() { // On each .selected cell... $('.selected').each(function() { // Get .selected data-id let idx = $(this).data('id'); // Find its counterpart let otherCell = $(`.marked${idx}`); // Get the value of .selected's hidden input let zer00ne = $(this).find(':hidden').val(); // Get the value of counterpart's hidden value let other01 = otherCell.find(':hidden').val(); // Replace the contents with one another $(this).html(`${other01}<input type="hidden" value="${other01}">`); otherCell.html(`${zer00ne}<input type="hidden" value="${zer00ne}">`); }); // Cleanup all of the cells $('td').each(function() { this.className = ''; $('.selected').removeData(); }); }); 
 body { font-size: 30px; text-align: center; background-color: ivory; } table { width: 100px; } h1 { font-family: Helvetica; font-size: 30px; } th { border: 10px solid black; padding: 5px; font-size: 70px; } td { border: 10px solid black; padding: 5px; font-size: 130px; } tr.center, td.center { text-align: center; } td:not(.notSelectable) { cursor: pointer } td.selected, td.lastSelected { background-color: gold; color: black; } td[class^=marked] { background-color: black; color: gold; } 
 <button>Crossover</button> <br /><br /> <table border="1" align="center"> <tbody> <tr> <td bgcolor="#4caf50">0<input type="hidden" value="0" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <td bgcolor="#4caf50">0<input type="hidden" value="0" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <td bgcolor="#4caf50">0<input type="hidden" value="0" /></td> <td bgcolor="#4caf50">0<input type="hidden" value="0" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <td bgcolor="#4caf50">1<input type="hidden" value="1" /></td> <th>P1</th> </tr> <tr> <td bgcolor="#ff0000">0<input type="hidden" value="0" /></td> <td bgcolor="#ff0000">0<input type="hidden" value="0" /></td> <td bgcolor="#ff0000">0<input type="hidden" value="0" /></td> <td bgcolor="#ff0000">1<input type="hidden" value="1" /></td> <td bgcolor="#ff0000">1<input type="hidden" value="1" /></td> <td bgcolor="#ff0000">1<input type="hidden" value="1" /></td> <td bgcolor="#ff0000">0<input type="hidden" value="0" /></td> <td bgcolor="#ff0000">1<input type="hidden" value="1" /></td> <td bgcolor="#ff0000">1<input type="hidden" value="1" /></td> <td bgcolor="#ff0000">0<input type="hidden" value="0" /></td> <th>P2</th> </tr> </tbody> </table> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Looks like you're assigning the value of one element to the other without first saving the original value. So both of them end up with the value of the second.

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