Home > Blockchain >  How to correctly retrieve and change the text's value stored from an array in jQuery?
How to correctly retrieve and change the text's value stored from an array in jQuery?

Time:10-06

I'm trying to change each <th> tag with the string values stored in an array. If it reaches the end of the array length, it'll just reset the counter which I already have implemented. I want to be able to keep looping and changing each of the header text values until the end of the table. I've tried several code attempts to be able to change and output the header text below (but none worked; no console error outputs either):

$(this).text() == headerTitleArr[headerIndex];
//$(this).text(headerTitleArr[headerIndex])[thIndex];
//$(this).css("content", headerTitleArr[headerIndex]);

I debugged the code to see what both values were returning and both of them return string values but for some reason, the values from the array headerTitleArr[headerIndex] are not being passed over to $(this).text() which is suppose to be the DOM selector of tr.table tr > th and thus remains the same as you see in console.log output.

Here's my jsfiddle of the issue.

Code Snippet:

if (window.matchMedia('(max-width: 2799px)').matches) {
  // do functionality on screens smaller than 2799px

  var headerTitleArr = ["Players","Stamina","Home Runs"];
  var headerTitleArrLength = 2;
  var mainChart = $("#chart1");
  var headerIndexCount = 0;
  // loop thru each of the tr.table-tr rows tracked by index and change the th text's index with the header text value
  $("#chart1 tr.table-tr > th").each(function(thIndex) {
    headerIndex = headerIndexCount;

    // TO FIX
    $(this).text() == headerTitleArr[headerIndex];
    //$(this).text(headerTitleArr[headerIndex])[thIndex];
    //$(this).css("content", headerTitleArr[headerIndex]);
    
    headerIndexCount  ;

    // if headerIndex equals to the length of the array, reset value
    if (headerIndex == headerTitleArrLength) {
      headerIndexCount = 0; // reset value
    }
  });
}

CodePudding user response:

I think it is here:

Change

$(this).text() == headerTitleArr[headerIndex];

to

$(this).text(headerTitleArr[headerIndex]);

  • Related