0

I have a database column that populates a label. It is date format so it saves entries as yy-mm-dd 00:00.0. I used this code to change it to the format that I wanted when it is listed.

var yyyymmdd = value.split(" ")[0].split("-");
return yyyymmdd[1] + "-" + yyyymmdd[2] + "-" + yyyymmdd[0];

Now I need to possibly change the color and this is the code I use to do it.

if(value.dead){
         $(element).css({"color": "#E33"});
      }else if(value.pairout){
         $(element).css({"color": "#0c9999"});

      }
return value.Date;

My question is: how can I combine both of these codes to make them work together to reorder the date and possibly change the color.

2 Answers2

5

A single value is returned via return from a function. This value can be any primitive, object or the result from an expression. So, if you wanted to return more than one value you could use either an object or an array.

Jason Cust
  • 10,743
  • 2
  • 33
  • 45
1

If those two are separate functions, say getDate(value) and getColor(value), do var combined = { date: getDate(value), color: getColor(value) }; and returned combined. The color setting might need to be refactored so to not assign the color to $(element) but just do the detection and return the color code.

Like so:

function getDate(value) {
  var yyyymmdd = value.split(" ")[0].split("-");
  return yyyymmdd[1] + "-" + yyyymmdd[2] + "-" + yyyymmdd[0];
}

function getColor(value) {
  if (value.dead) return '#E33';
  if (value.pairout) return '#0c9999';
  
  return null; //not handled
}

function getCombined(aDate, value) {
  return { date: getDate(aDate), color: getColor(value) };
}

var aDate = '15-01-01 15-02-14';
var foo = { dead : true, pairout: false };

var value = getCombined(aDate, foo);

if (value.color) $('#foo').css({ color : value.color });
$('#date').text(value.date);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='foo'>FOO!</div>
<div id='date'></div>
Jimmy Chandra
  • 6,472
  • 4
  • 26
  • 38