Home > Blockchain >  JQuery conditional format td after Ajax Get
JQuery conditional format td after Ajax Get

Time:10-25

I have a webpage with the following format:

<!doctype html>

<html>
 <body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainstyle.css') }}">
 <script>
     setInterval(function ajaxCall1() {
     $.ajax({
        url: "/nfl_data",
        type: "GET",
        dataType: "json",
        })
        .done( function (response) {
            var tableHTML = '';
            tableHTML  = '<tr><th colspan="1"> Game Date </th><th> Team 1</th><th colspan="2">Probability </th><th>Team 2 </th><th colspan="2">Score </th></tr>';

            $.each(response, function (i, item) {
                tableHTML  = '<tr><td>'   item.GameDate   '</td><td>'   item.Team1  '</td><td>'   item.Team1Prob   '</td><td>'   item.Team2Prob   '</td><td>'   item.Team2   '</td><td id="team1-score">'   item.Team1Score   '</td><td id="team2-score">'   item.Team2Score '</td></tr>';
            });
            $("#game-data").html(tableHTML);
        });
    }, 1000 * 1);
  </script>
  <div id="pageHead">
      
  </div>
  
  
    <div id="game-wrapper">
        <table  id="game-data">

    </table>
    </div>
    <script>
    $.when(ajaxCall1()).done(function(){
        var t1score = document.getElementById('team1-score')
        var t2score = document.getElementById('team2-score')
        
        for (var i=0, len=t1score.length; i<len; i  ){
            if (parseInt(t1score[i].innerHTML)>parseInt(t2score[i].innerHTML)){
                t1score[i].style.backgroundColor = "#e8630a";
            }
            else if (parseInt(t1score[i].innerHTML)<parseInt(t2score[i].innerHTML)){
                t2score[i].style.backgroundColor = "#e8630a";
            }
        }
        });
    
    </script>
 </body>
</html>

I'm very new to JQuery.

I'd like to conditionally format the game score cells based on which value is larger.

The bottom JQuery script is intended to format the tabular data with the id team1-score and team2-score.

However, on page load, the table is empty until the ajaxCall1 retrieves the data. I'm getting an error when I run this which is an Uncaught Reference Error, the ajaxCall1 is not defined.

I'm assuming its because JQuery is not defining the ajaxCall1 function until the setInterval triggers.

My desired output is that the JQuery highlights the td with id team1-score and team2-score based on which is larger.

i.e. if id team1-score is larger, it gets colored with: #e8630a

Thank you.

CodePudding user response:

You never actually define ajaxCall1(), only immediately invoke it from the interval. This makes it an anonymous function and not usable anywhere else. Also that's a terrible name for a function, you should name it for what it's doing, something like UpdateScores()

In this case, I don't really see why you would do these things separately? You could put it all in the same <script> and remove the need to loop through everything twice.

<!doctype html>
  <head>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='styles/mainstyle.css') }}">
    <style>
      .winner.team{
        backgroundColor: '#e8630a';}
    </style>
  </head>
  <body>

  <div id="pageHead"></div>      
  <div id="game-wrapper">
    <table  id="game-data"></table>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    //let UpdateScores = function() {}; //this is a function expression
    //function UpdateScores() {} //this is a function declaration (not inside of another function)
    //these can be called from elsewhere in the code

    setInterval(function UpdateScores() { //this is an anonymous function, it can not be called elsewhere
      $.getJson('/nfl_data')
        .error(function(error) {
          //code to handle errors
        })
        .done(function (response) {
          let tableHTML = `
            <tr>
              <th colspan="1">Game Date</th>
              <th>Team 1</th>
              <th colspan="2">Score</th>
              <th colspan="2">Probability</th>
              <th>Team 2</th>
              <th colspan="2">Probability</th>
              <th colspan="2">Score</th>
            </tr>`;

            $.each(response, function (i, item) {
                tableHTML  = `
                 <tr>
                   <td>${item.GameDate}</td>
                   <td>${item.Team1}</td>
                   <td>${item.Team1Prob}</td>
                   <td hljs-subst">${item.Team1Score > item.Team2Score ? ' winner': ''}">${item.Team1Score}</td>
                   <td>${item.Team2Prob}</td>
                   <td>${item.Team2}</td>
                   <td hljs-subst">${item.Team2Score > item.Team1Score ? ' winner': ''}">${item.Team2Score}</td>
                 </tr>`;
            });

            $('#game-data').html(tableHTML);
        });
      }, 1000);       
    </script>
  </body>
</html>

foot notes:

  • ids are only meant to be used once. If you want to identify groups of things, you can use classes. Classes also allow you to apply css rules, rather than modifying each element individually.

  • making an ajax call every second is going to consume alot of resources.

  • I prefer putting <script> at the bottom of the <body>, that way the scripts are only run after the body is loaded, which prevents some other challenges.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

  • Related