From HTML table to JS array

Viewed 58

I created an HTML table where some values can be changed using a slider. The problem is that when I try to retrieve the value from the table the changes are not saved.

My goal would be to retrieve the value from the HTML table to then calculate a dot product of each row with another array.

This is the HTML code that I have used to create the slider and the table

<input type="range" name="mySlider" id=mySlider min="0" max="1" step="0.1" value="0.5", onchange="updateSlider(this.value)">

<div id="sliderAmount"></div>

<table id = "user_feature">
  <tr>
    <th>User</th>
    <th>Feature One</th>
    <th>Feature Two</th>
  </tr>
  <tr>
    <td>Anna</td>
    <td>0.3</td>
    <td>0.4</td>
  </tr>
  <tr>
    <td>Jonny</td>
    <td>0.7</td>
    <td>0.1</td>
  </tr>
</table> 

And this is the JS code that I have used to change the value of one cell, retrieve the values from the table (the current implementation does not capture the changes), and create a single array and not one for each row.

function updateSlider(slideAmount) {
  var cell_change = document.getElementById("user_feature").rows[1].cells;
  cell_change[1].innerHTML = slideAmount;
}

var matrix = [];

var oTable = document.getElementById('user_feature');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 1; i < rowLength; i++) {

  //gets cells of current row
  var oCells = oTable.rows.item(i).cells;

  //gets amount of cells of current row
  var cellLength = oCells.length;

  //loops through each cell in current row
  for (var j = 0; j < cellLength; j++) {
    var cellVal = oCells.item(j).innerHTML;
    matrix.push(cellVal);
  }
}
1 Answers

as commenter said, put this into a function and call it when slider is slid:

function updateSlider(slideAmount) {
  var cell_change = document.getElementById("user_feature").rows[1].cells;
  cell_change[1].innerHTML = slideAmount;
  CacheValues();
}

var matrix = [];

function CacheValues(){

var oTable = document.getElementById('user_feature');

//gets rows of table
var rowLength = oTable.rows.length;

//loops through rows    
for (i = 1; i < rowLength; i++) {

  //gets cells of current row
  var oCells = oTable.rows.item(i).cells;

  //gets amount of cells of current row
  var cellLength = oCells.length;

  //loops through each cell in current row
  for (var j = 0; j < cellLength; j++) {
    var cellVal = oCells.item(j).innerHTML;
    matrix.push(cellVal);
  }
}
}

CacheValues();

Related