2

I'd like to do a small function that would permute 2 cells of a table with jQuery (or PHP/Ajax). Let's say I have the following table:

<table class="table">
    <tr>
        <td class="btn" data-cellN="1">
            01
        </td>
        <td class="btn" data-cellN="2">
            02
        </td>          
    </tr>

    <tr>
        <td class="btn" data-cellN="3">
            05
        </td>
        <td class="btn" data-cellN="4">
            06
        </td>
    </tr>
</table>   

How to select 2 cells and permute them?

EDIT:

I made my way through the function thanks to your advice, nevertheless. It is working the first time bug I got a weird bug coming from the c1 c2 c3 variables, I don't know why, could anyone help me to finish my function please?

Here is my Javascript: (it is wrapped in a doc ready)

        var nbbuttonclicked=0; // to trigger the movecell function after the second button was clicked
        var count=0; //Number of tinme we moved a cell

        var table = {

            c1:null,
            c2:null,
            c3:null,

            check: function(){
                $('td').on('click', function(){ //When the user click on a button we verify if he already clicked on this button

                    if( $(this).hasClass('btn-info') ) {

                        //If yes, then remove the class and variable c1
                        $(this).removeClass('btn-info');
                        table.c1=0;
                        nbbuttonclicked--;

                    }else{
                        //if no, then add a class to show him it is clicked and remember the value of the cell
                        $(this).addClass('btn-info');
                        if( typeof table.c1 === 'undefined' || table.c1===null) {
                            table.c1 = $(this);
                          console.log('c1:'+table.c1.html());
                        }else{
                            table.c2 = $(this);
                          console.log('c2:'+table.c2.html());
                        }

                        nbbuttonclicked++;

                        if( nbbuttonclicked==2 ) {
                            table.movecell(table.c1,table.c2); // we trigger the function to permute the values
                        }
                    }
                });
            },

            movecell: function(c1, c2){
                //We reset that variable for the next move
                nbbuttonclicked=0;

              //we move the cells
              table.c3=c1.html();
              c1.html(c2.html());
              c2.html(table.c3)

              c1.removeClass('btn-info');
              c2.removeClass('btn-info');
              table.c1=table.c2=table.c3=c1=c2=null;

            },

            // movecell: function(c1, c2){
                // We check if the cells.html() are = to data-cellN. If yes, you won
                // foreach()
            // },

            // var row = $('table tr:nth-child(1)')[0];
            // moveCell(row, 0, 3);
        };
        table.check();

and here is a sample: http://jsbin.com/exesof/2/edit

5
  • You mean when you change table values also its affects into db?
    – Ranjith
    Mar 12, 2013 at 12:53
  • I think he means to merge them, but am not sure xD
    – aleation
    Mar 12, 2013 at 12:57
  • Your HTML markup is invalid.
    – Eli
    Mar 12, 2013 at 13:00
  • I just fixed it xD lets see if he accepts the edit
    – aleation
    Mar 12, 2013 at 13:01
  • thanks for the edit guys, yes, I want to replace/permute the value of the concerned td
    – Miles M.
    Mar 12, 2013 at 13:55

4 Answers 4

1

Try this code:

var cell0,
    cell1,
    next,
    row0,
    row1;

$('td').on('click', function() {
  if(!cell0) {
    cell0 = this;
    row0 = cell0.parentNode;
    return;
  } else if(!cell1) {
    cell1 = this;
    row1 = cell1.parentNode;

    // === Switch cells ===
    next = cell0.nextSibling;
    row1.insertBefore(cell0, cell1);
    row0.insertBefore(cell1, next);
    // ====================

    row0 = row1 = cell0 = cell1 = next = null;
  }
});

Working example you can try here: http://jsbin.com/irapeb/3/edit

Click one of the cells, than another one and see they are switched :)

3
  • thx man, but I realized that I don't need to permute the td but only their value, so that when I have the numbers in the right order (1234...) it triggers an event. So I'd like to simply change the html value of the td. Look at my code, I did it with jquery, but for some reason, I got a bug with the permutation after the first one. Do you have any idea why does that happen ?
    – Miles M.
    Mar 12, 2013 at 21:14
  • 1
    You can't use this.movecell since it will be called in the scope of jQuery callback function and this will be window in that case. Your code has a bug - you called arguments of movecell same as global variables, thus you nullify these arguments and not the global vars.
    – Vadim
    Mar 12, 2013 at 22:06
  • that was it. But I don't understand what happen to c1 and c2 when I have them from this movecell: function(c1,c2) are they global variables here or just inside the fct ? I just edited my answer again
    – Miles M.
    Mar 12, 2013 at 23:04
1

This code will move the 4th td (referenced as cell[3]) on place of the first cell (cell[0]) in the first row (and the 1st becomes the 4th):

function moveCell(row, c1, c2) {
    var cell = row.cells;
        arr = [c1, c2].sort(),
        c1 = arr[1],
        c2 = arr[0];
    row.insertBefore(row.insertBefore(cell[c1], cell[c2]).nextSibling, cell[c1].nextSibling);
}

var row = $('table tr:nth-child(1)')[0];
moveCell(row, 0, 3);

http://jsfiddle.net/2N2rS/3/

I wrote this function to simplify process. It uses native table methods.

Modifying the number of row (:nth-child(1)) and indexes of the table cells you can permute them as you need.

4
  • Thanks,I'm more familiar with jQuery. Is there a way to do it with jQuery ?
    – Miles M.
    Mar 12, 2013 at 14:09
  • In this case jQuery will not give a lot of advantages. Select necessary row in the table and pass it with td indexes to the function I wrote.
    – dfsq
    Mar 12, 2013 at 14:22
  • got it, Well I'm doing $('td').on('click',function() { //move cell }); but how to wait for the second button to be clicked ? Thx
    – Miles M.
    Mar 12, 2013 at 14:26
  • What buttons are talking about?
    – dfsq
    Mar 12, 2013 at 15:15
1

with jQuery, you can do it with:

$(document).ready(function() {

    $("table.table tbody tr td:first-child").each(function(index, element) {
    // this and element is the same    
    $(this).insertAfter($(this).next());
    });

});

Assuming you don't ommited the tbody element (which is automatically added by some browser as default behaviour)

working example

If you want to do the process when clicking on the first cell, you just have to use on with click event instead of each.

$(document).ready(function() {

    $("table.table tbody tr td:first-child").on('click', function(clickEvent) {
        $(this).insertAfter($(this).next());
    });

});
1
  • Thanks, I need to select a cell when clicking on it, so i guess I would use onclick or on('click') but I don't really know how
    – Miles M.
    Mar 12, 2013 at 14:09
0

This can be done in pure javascript:

  1. Fetch clicked sell count;
  2. Fetch data of both cells, when they are selected;
  3. Replace cell values with the opposite ones;
  4. Store new values in DB via ajax call.

Now it's up to you to write the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.