mercredi 3 février 2016

Better way to do multiple instances of IF statements when appending HTML?

Okay, so I have a script in Google Apps Script driven Web App, where I have a set of data in a Google Spreadsheet like so:

enter image description here

And in my code.gs I define my spreadsheet and get all the values, then I iterate through all of them and create variables that I then return as a JSON, like so:

function getOrders(){
 var ordersName = [];
 var subRange = sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn());
 var orders = subRange.getValues();

 for (var i = 0; i < orders.length; i++) {
    ordersName.push( { 
       status: orders[i][0], 
       type: orders[i][1],
       answer: orders[i][2]
   } );
  }
  return JSON.stringify(ordersName);
}

Earlier in my code.gs I also have an HTMLservice, creating an HTML page from the file page.html.

I run my function from my page.html like so:

$(function() {
  google.script.run.withSuccessHandler(buildOrderList).getOrders();
});

function buildOrderList(ordersName) {
  var arr = JSON.parse(ordersName);
  var rows = $('#orders');
  for (var i = 0; i < arr.length; i++) {

    rows.append('<div class="status">' + arr[i].status + '</div><div class="type">' + arr[i].type + '</div><div class="answer">' + arr[i].status + '</div>) 

Then that JSON is parsed into my function buildOrderList, and then I use append to display the daya in an HTML element with the ID "orders" all that works fine. What I can then do is style the various div's that I created in the append, based on their class. So everything in status could have color: blue, and everything in type could be red and so on.

But if I want for there to be a difference in NEW and COMPLETED, that are in the same column, the I would have to do conditional logic, like this:

 if(arr[i].status === "NEW"){
 rows.append('<div class="status-new">' + arr[i].status + '</div>....)} 

 if(arr[i].status === "COMPLETED"){
 rows.append('<div class="status-completed">' + arr[i].status + '</div>....)} 

Where I then just append a div with a different class for each of the, status-new and status-completed. Which also "works" fine, but soon seems quite cumbersome, if I also would like to make the same distinction between LARGE and SMALL and ANSWERED and UNANSWERD. I would then need 8 different versions of the IF statements?

So my question is is there a way to make some conditional logic that defines the individual divs with their respective classes, before they are being appended? so first we see what the status is, okay it's NEW, so I this will be the HTML, then we see the type it's Large so this HTML, and so on.. and when done with everything in that row you move on to the next one.

I have tried some stuff, but I can't quite wrap my head around how it work outside of an extremely long IF IF IF IF THEN this.

All help is very much appreciated :)

Aucun commentaire:

Enregistrer un commentaire