How to compare cells in JavaScript table to each other and test for equality? How does indexOf work?

后端 未结 2 862
温柔的废话
温柔的废话 2021-01-07 15:01

I created a table in my HTML code. It has 9 columns and 13 rows. It gets filled up completely by a JavaScript loop that fills it with names of people from a few arrays. Howe

2条回答
  •  执念已碎
    2021-01-07 15:20

    You should get an array of rows, each row is an array of cells. That way the validation is much easier. I'm not sure about how you want to show the conflict. In this demo I've just highlight the duplicated cells (conflicted) in red (at least I like this kind of showing conflict rather than modifying the conflicted cells' text).

    HTML:

    123
    156
    787
    8910

    CSS:

    td {
      width:100px;
      height:50px;
      border:1px solid black;
    }
    table {
      border:1px solid black;
      border-collapse:collapse;
    }
    td.invalid {
      background:red;
    }
    

    JS:

    $('td').attr('contenteditable',true);
    var cell;     
    function highlight(){    
      $(arguments).toggleClass('invalid',true);
    }
    function checkConstraints(e){
      //reset style before re-checking
      $('td.invalid').toggleClass('invalid');
      //get rows as an array of array
      var rows = $('tr').map(function(elem,i){
          return [$(this).children('td').toArray()];
      }).toArray();        
      //loop through the rows
      for(var i = 0; i < rows.length; i++){
        cell = {};        
        for(var j = 0; j < rows[i].length; j++){
            var cellText = $(rows[i][j]).text();
            if(cell[cellText]) {  
                highlight(cell[cellText], rows[i][j]);                
            } else {
                cell[cellText] = rows[i][j];
            }
            if(i < rows.length - 1 && 
               cellText == $(rows[i+1][j]).text()){
               highlight(rows[i][j],rows[i+1][j]);
            }            
        }        
      }
    }
    $('button').click(checkConstraints);
    

    Demo.

    Note that, I set contenteditable for all the cells (td), you can edit the cells text to what you want and click the button to test the demo.

提交回复
热议问题