0

I have this code below that popups the cell value whenever the user clicks a specific cell.

What I'm currently trying to do is when the user clicks a cell i want that cell value to be appended to another column. I tried using the push method but it doesn't seem to be working. I'm not sure if I'm doing it the wrong way

JFiddle

HTML:

<table id="fruitsTable" class="fruitstableroni skillsTable class">
    <thead></thead>
    <tbody></tbody>
</table>

JavaScript:

var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
        for (var j = 0; j < tbl.rows[i].cells.length; j++)
            tbl.rows[i].cells[j].onclick = function () { 
                obj[key2].push(this); //Trying to push it to the second column.
                console.log(this);
            };
    }
}
function getval(cel) {
    //console.log(cel.innerHTML);
}

var obj = {};

var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);

var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);

var key3 = "Random Fruits";
obj[key3] = ['Soursop', 'Papaya', 'Pineapple', 'Melon'];
var myArray3 = [];
myArray3.push(obj);

var $header = $("<tr>"),
  cols = 0,
  bodyString = "";

$.each(obj, function(key, values) {
  cols = Math.max(cols, values.length); // find the longest
  $header.append($('<th/>').text(key + ": " + values.length));
});
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
  bodyString += '<tr>';
  $.each(obj, function(key, values) {
    bodyString += '<td>' +
      (values[i] ? values[i] : "") + // ternary - instead of using if/else
      '</td>';
  });
  bodyString += '</tr>';
}
$('.fruitsTableClass thead').html($header);
$('.fruitsTableClass tbody').html(bodyString);

var tbl = document.getElementById("fruitsTable");
if (tbl != null) {
  for (var i = 0; i < tbl.rows.length; i++) {
    for (var j = 0; j < tbl.rows[i].cells.length; j++)
      tbl.rows[i].cells[j].onclick = function() {
        getval(this);
        obj[key2].push(this);
      };
  }
}

function getval(cel) {
  alert(cel.innerHTML);
}
.class {
  font-family: Open Sans;
}

.center {
  display: flex;
  justify-content: center
}

.skillsTable th {
  border-left: 1px solid #AAA5A4;
  border-right: 1px solid #AAA5A4;
}

table {
  float: left;
  border-collapse: collapse;
  width: 70%
}

td {
  border-left: 1px solid #AAA5A4;
  border-right: 1px solid #AAA5A4;
  padding-top: 8px;
  padding-left: 11px;
  font-size: 15px;
}

th {
  color: #0080ff;
  font-weight: normal;
  border-bottom: 1px solid #AAA5A4;
  padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
  <table id="fruitsTable" class="fruitsTableClass skillsTable class">
    <thead></thead>
    <tbody></tbody>
  </table>
</div>

3
  • Well just pushing something to an array, will not make your tables change in any way … if you want that to happen, then you need to implement it. Commented Jun 11, 2018 at 7:51
  • 1
    @Bobby did some small changes in jsfiddle.net/gnm8wv5f which will point you to right direction. Go through the code and see why changes were done. Commented Jun 11, 2018 at 7:52
  • What column do you want to append what value to? Please show expected output (I recognise some of the code ;) - you want to change obj[key2].push(this); to something like this.parentNode.cells[2].innerHTML+= this.innerHTML Commented Jun 11, 2018 at 7:55

4 Answers 4

1

Restructure your code to have a method to redraw UI and to enable event listeners:

function redraw (obj) {

  var $header = $('<tr>'),
    cols = 0,
    bodyString = ''

  $.each(obj, function (key, values) {
    cols = Math.max(cols, values.length) // find the longest
    $header.append($('<th/>').text(key + ': ' + values.length))
  })
  for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
    bodyString += '<tr>'
    $.each(obj, function (key, values) {
      bodyString += '<td>' +
        (values[i] ? values[i] : '') + // ternary - instead of using if/else
        '</td>'
    })
    bodyString += '</tr>'
  }
  $('.fruitsTableClass thead').html($header)
  $('.fruitsTableClass tbody').html(bodyString)
}

function listener (obj) {
  tbl = document.getElementById('fruitsTable')
  if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
      for (var j = 0; j < tbl.rows[i].cells.length; j++)
        tbl.rows[i].cells[j].onclick = function () {
          getval(this)
          obj[key2].push(this.innerHTML)
          redraw(obj)
          listener(obj)
        };
    }
  }
}

function getval (cel) {
  alert(cel.innerHTML)
}

redraw(obj)
listener(obj)

JSFiddle - https://jsfiddle.net/gnm8wv5f/

Sign up to request clarification or add additional context in comments.

Comments

0

To add rows or cells to a table, you should use the methods insertRow() and insertCell().

Example, if you want to add a cell at the beginning of a row (from w3schools):

var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";

Or, to insert at the end:

var x = row.insertCell(row.cells.length);

Using cells.length you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.

More info in: w3 | MDN

Comments

0

Try this code.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var daraArray=[];   
$(document).ready(function(){
    $(".classTd").click(function(){
       //console.log($(this).html());
       daraArray.push($(this).html());
       console.log(daraArray);
    });
});
</script>

<style type="text/css">
    .classTd{
        text-align: center;
    }
</style>
</head>


<table id="fruitsTable" class="fruitstableroni skillsTable class" border="1">
    <thead></thead>
    <tbody>
        <tr>
            <td class="classTd" width="10%">1</td>
            <td class="classTd" width="10%">2</td>
            <td class="classTd" width="10%">3</td>
        </tr>

        <tr>
            <td class="classTd" width="10%">4</td>
            <td class="classTd" width="10%">5</td>
            <td class="classTd" width="10%">6</td>
        </tr>

        <tr>
            <td class="classTd" width="10%">7</td>
            <td class="classTd" width="10%">8</td>
            <td class="classTd" width="10%">9</td>
        </tr>
    </tbody>
</table>
</html>

1 Comment

If you want to make it string. var str = daraArray.join(',');
0

The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.