简体   繁体   中英

Sorting table with jQuery after rows are updated via ajax call

Part of my website has an election section where we update election numbers as they come in. Previously, to see new results you had to refresh the page.

I have working code that will request a custom rest API with live numbers and have the jquery code pulling the data in and updating the required table td with the new information without the need to refresh. Unfortunately, this code does not resort the table when the new numbers are updated.

If candidate a is winning but the ajax call updates the numbers and now candidate b is winning, I want to sort the table so that candidate a is in the first row.

I have a working jsfiddle and will post the code I have below. I have tried various different things to sort the table rows after the function that pulls in the new numbers to no avail.

When a user clicks the checkbox, a function runs that runs every 1 second (just for testing purposes.) When a user unchecks the code, the requests stop.

I want to sort by the percentage column after the new numbers after been added.

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" integrity="sha512-oc9+XSs1H243/FRN9Rw62Fn8EtxjEYWHXRvjS43YtueEewbS6ObfXcJNyohjHqVKFPoXXUxwc+q1K7Dee6vv9g==" crossorigin="anonymous" />

<div class="custom-control custom-checkbox mt-2 ml-2">
    <input type="checkbox" class="custom-control-input" id="customCheck1">
    <label class="custom-control-label" for="customCheck1">Enable Live Results</label>
</div>
<table id="rprc" class="table table-bordered">
   <caption class="ml-2 small">(I) = Incumbent - Green Highlight = Winner</caption>
   <thead class="thead-dark">
      <tr>
         <th scope="col">Name</th>
         <th scope="col">Party</th>
         <th scope="col">Votes</th>
         <th scope="col">%</th>
      </tr>
   </thead>
   <tbody>
      <tr id="row-rprc-22938" class="small" data-percent="0">
         <td class="font-weight-bold"><a href="https://www.bamapolitics.com/alabama/alabama-government-officials/profiles/jerry-carl/">Jerry Carl</a></td>
         <td class="font-weight-bold">Republican</td>
         <td id="rprc-22938" class="font-weight-bold">0</td>
         <td id="rprc-22938-pct" class="font-weight-bold">0</td>
      </tr>
      <tr id="row-rprc-1359" class="small" data-percent="0">
         <td><a href="https://www.bamapolitics.com/alabama/alabama-government-officials/profiles/bill-hightower/">Bill Hightower</a></td>
         <td>Republican</td>
         <td id="rprc-1359">0</td>
         <td id="rprc-1359-pct">0</td>
      </tr>
   </tbody>
</table>

Javascript

var timeOut = '';

function getResults() {
    jQuery.getJSON('https://www.bamapolitics.com/wp-json/elections/v1/election/33159', function(data) {
        jQuery.each(data, function(i, value) {
            jQuery('#' + value.id).text(value.votes);
            jQuery('#' + value.id + '-pct').text(value.percent + '%');
            jQuery('#row-' + value.id).attr('data-percent', value.percent);
        });
    });
    timeOut = setTimeout(function() {
        getResults();
    }, 1000);
}
jQuery(function() {
    jQuery("#customCheck1").click(function() {
        if (jQuery(this).is(':checked')) {
            timeOut = setTimeout(function() {
                getResults();
            }, 1000);
        } else {
            clearTimeout(timeOut);
        }
    });
});

JSFiddle

https://jsfiddle.net/BWBama85/xq08cmnb/1/

I was able to get this working with jQuery tablersorter which is fine but would be interested in knowing if there is a simpler way that does not require a 3rd party extension.

For those that wish to see my working code:

HTML

<div class="custom-control custom-checkbox mt-2 ml-2">
    <input type="checkbox" class="custom-control-input" id="customCheck1">
    <label class="custom-control-label" for="customCheck1">Enable Live Results</label>
</div>
<table id="rprc" class="table table-bordered tablesorter">
   <caption class="ml-2 small">(I) = Incumbent - Green Highlight = Winner</caption>
   <thead class="thead-dark">
      <tr>
         <th scope="col">Name</th>
         <th scope="col">Party</th>
         <th scope="col">Votes</th>
         <th scope="col">%</th>
      </tr>
   </thead>
   <tbody>
      <tr id="row-rprc-1359" class="small" data-percent="0">
         <td><a href="https://www.bamapolitics.com/alabama/alabama-government-officials/profiles/bill-hightower/">Bill Hightower</a></td>
         <td>Republican</td>
         <td id="rprc-1359">1</td>
         <td id="rprc-1359-pct">75%</td>
      </tr>
      <tr id="row-rprc-22938" class="small" data-percent="0">
         <td><a href="https://www.bamapolitics.com/alabama/alabama-government-officials/profiles/jerry-carl/">Jerry Carl</a></td>
         <td>Republican</td>
         <td id="rprc-22938">2</td>
         <td id="rprc-22938-pct">25%</td>
      </tr>
   </tbody>
</table>

Javascript

var timeOut = '';

jQuery(function() {
    jQuery("#rprc").tablesorter({
        sortList: [
            [3, 1]
        ]
    });
});

function getResults() {
    jQuery.getJSON('https://www.bamapolitics.com/wp-json/elections/v1/election/33159', function(data) {
        jQuery.each(data, function(i, value) {
            jQuery('#' + value.id).text(value.votes);
            jQuery('#' + value.id + '-pct').text(value.percent + '%');
        });
        jQuery('#rprc').trigger("update");
    });
    timeOut = setTimeout(function() {
        getResults();
    }, 10 * 1000);
}
jQuery(function() {
    jQuery("#customCheck1").click(function() {
        if (jQuery(this).is(':checked')) {
            timeOut = setTimeout(function() {
                getResults();
            }, 10 * 1000);
        } else {
            clearTimeout(timeOut);
        }
    });
});

Updated JSFiddle

https://jsfiddle.net/BWBama85/xq08cmnb/20/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM