Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

brendon hanson
brendon hanson
6,191 Points

How can I sort a table numerically with jQuery?

I need to sort my table numerically based on the number in the quantityCell. I tried tablesort() but there are all sorts of errors

$(document).ready(function() {
  let partNum;
  let quantity;
  let description;
  let stockStatus = 'green';
  const table = $('table');

  $("#table").tablesort();
// WHen button is clicked you fill out prompts and then a new row with new info appears
$('.addItem').click(function() {
  while (true) {
     partNum = prompt("What is the part number?");
     quantity = prompt("What is the quantity of this part?");
     description = prompt("Describe this part");
    $("table").find('tbody').append( `<tr><td contenteditable='true'>${partNum}</td><td contenteditable='true'>${quantity}</td><td contenteditable='true'>${description}</td></tr>` );

    break;
  }
});
$('.navButtons').click(function() {
    $('.navButtons').removeClass("blue");
    $(this).addClass("blue");
});
$('.button1').click(function() {
  $("table").find('tbody').html(capacitorHtml);
  stockStatusFunc();
  if (stockStatus === 'green') {
    $('td').addClass('green');
  }
});
$('.button2').click(function() {
  $("table").find('tbody').html(electricalHTML);
  stockStatusFunc();
  if (stockStatus === 'green') {
    $('td').addClass('green');
  }
});
function stockStatusFunc() {
  $('table tr').each(function(){
    $(this).find('td ~ .quantityCell').each(function(){
      let int = parseInt($(this).text());
      console.log(int);
      if (int <= 5) {
        $(this).removeClass('green');
        $(this).removeClass('yellow');
        $(this).addClass('red');
      }else if (int <= 15 && int > 5) {
        $(this).removeClass('green');
        $(this).removeClass('red');
        $(this).addClass('yellow');
      } else {

      }
    });
});
}
    });

1 Answer

take a look at datatables it might be what you are after

brendon hanson
brendon hanson
6,191 Points

Thanks! I've been looking for something like this all day!