Deciding the value in console log based on the column value

475 views Asked by At

Please take a look at my code below. I have a YearEligible column with Y and N values in the cell for each record. Based on this I want to decide what values does the Year column sends upon clicking Get rows button.

Explanation in detail regarding my requirement:

Let's say If I have checked the very first row ( as shown in the image below):
enter image description here

When I click on the Get rows button, I can see the following in console.log which looks good:

[{
  available: true,
  boundindex: 0,
  firstname: "Mayumi",
  lastname: "Nagase",
  price: 3.25,
  productname: "Espresso con Panna",
  quantity: 6,
  total: 19.5,
  uid: 0,
  uniqueid: "2128-24-28-17-311629",
  visibleindex: 0,
  yeareligible: "Y",
  yearValue: "2011"
}]

However, let's say if I select a record where the Year Eligible column has a value of N and click on the Get rows button, I see the following in console.log:

[{
  available: true,
  boundindex: 1,
  firstname: "Regina",
  lastname: "Davolio",
  price: 3.3,
  productname: "Doubleshot Espresso",
  quantity: 8,
  total: 26.4,
  uid: 1,
  uniqueid: "2917-25-23-18-212828",
  visibleindex: 1,
  yeareligible: "N"
}]

My observation:

The above console.log is not returning anything for yearValue, which makes sense since I didn't select anything.

My Questions:

  1. In above scenario, is it possible to return a default value of yearValue as -1 ? Basically I want to include yearValue as -1 when a user selects a record with Year Eligible value set to N.

  2. Display N/A on the cell under Year column for which the Year Eligible column has a value of N ?

  var data = new Array();
  var firstNames = [
      "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"];
  var lastNames = [
      "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"];
      var yearEligible = [
      "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"];
  var productNames = [
      "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"];
  var priceValues = [
      "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"];
  for (var i = 0; i < 10; i++) {
      var row = {};
      var productindex = Math.floor(Math.random() * productNames.length);
      var price = parseFloat(priceValues[productindex]);
      var quantity = 1 + Math.round(Math.random() * 10);
      row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
      row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];
      row["yeareligible"]= yearEligible[Math.floor(Math.random() * lastNames.length)];
      row["productname"] = productNames[productindex];
      row["available"] = !!(i % 2);
      row["price"] = price;
      row["quantity"] = quantity;
      row["total"] = price * quantity;
      data[i] = row;
  }
  var source = {
      localdata: data,
      datatype: "array"
  };
  var dataAdapter = new $.jqx.dataAdapter(source, {
      loadComplete: function (data) {},
      loadError: function (xhr, status, error) {}
  });
  $("#jqxgrid").jqxGrid({
      theme: 'energyblue',
      width: 500,
      autoheight: true,
      editable: true,
      source: dataAdapter,
      columns: [{
          text: 'Available',
          datafield: 'available',
          width: 100,
          columntype: 'checkbox'
      }, {
          text: 'First Name',
          datafield: 'firstname',
          width: 100
      }, {
          text: 'Last Name',
          datafield: 'lastname',
          width: 100
      }, {
          text: 'Year Eligible',
          datafield: 'yeareligible',
          width: 100
      },
       {
          text: 'Year',width: 120,datafield:'yearValue' , columntype: 'dropdownlist', editable: true,
          createeditor: function (row, column, editor) {
                    var list = ['2010', '2011', '2012' ,'2013','2014','2015','2016','2017','2018','2019','2020','2021'];
                  
                   
                     
                    editor.jqxDropDownList({ autoDropDownHeight: true, source: list, selectedIndex: 0 });
                }
       
      },
      {
          text: 'Product',
          datafield: 'productname',
          width: 180
      }, {
          text: 'Quantity',
          datafield: 'quantity',
          width: 80,
          cellsalign: 'right'
      }, {
          text: 'Unit Price',
          datafield: 'price',
          width: 90,
          cellsalign: 'right',
          cellsformat: 'c2'
      }, 
     
      
      {
          text: 'Total',
          datafield: 'total',
          width: 100,
          cellsalign: 'right',
          cellsformat: 'c2'
      }]
  });
  
   $('#jqxbutton').click(function () {
    var rows = $('#jqxgrid').jqxGrid('getrows');
  
     var selectedRows = rows.filter(x => x.available)
     
    console.log(selectedRows)
   
     //alert(rows);
 });
  
 
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet"/>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />

Edited: Testing for the default value of 2016 and aggregate based on Calculuswhiz's answer:

let firstNames = [
  "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", 
  "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
];

let lastNames = [
  "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", 
  "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", 
  "Vileid", "Saylor", "Bjorn", "Nodier"
];

let yearEligible = [
  "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"
];

let productNames = [
  "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", 
  "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", 
  "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
];

let priceValues = [
  "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
];

let data = [];
for (let i = 0; i < 10; i++) 
{
  let productindex = Math.floor(Math.random() * productNames.length);
  let price = parseFloat(priceValues[productindex]);
  let quantity = 1 + Math.round(Math.random() * 10);
  let row = {
    firstname : firstNames[Math.floor(Math.random() * firstNames.length)],
    lastname : lastNames[Math.floor(Math.random() * lastNames.length)],
    yeareligible : yearEligible[Math.floor(Math.random() * lastNames.length)],
    productname : productNames[productindex],
    available : !!(i % 2),
    price : price,
    quantity : quantity,
    total : price * quantity
  };
  data.push(row);
}

let source = {
  localdata: data,
  datatype: "array"
};

let dataAdapter = new $.jqx.dataAdapter(source,
{
  loadComplete: function(data) {},
  loadError: function(xhr, status, error) {}
});

$("#jqxgrid").jqxGrid(
{
  theme: 'energyblue',
  width: 500,
  autoheight: true,
  editable: true,
  source: dataAdapter,
  columns: [{
      text: 'Available',
      datafield: 'available',
      width: 100,
      columntype: 'checkbox'
      
    }, {
      text: 'First Name',
      datafield: 'firstname',
      width: 100
    }, {
      text: 'Last Name',
      datafield: 'lastname',
      width: 100
    }, {
      text: 'Year Eligible',
      datafield: 'yeareligible',
      width: 100
    },
    {
      text: 'Year',
      width: 120,
      datafield: 'yearValue',
      columntype: 'dropdownlist',
      editable: true,
      createeditor: function(row, column, editor) 
      {
        let list = [
          '2010', '2011', '2012', '2013', '2014', '2015', 
          '2016', '2017', '2018', '2019', '2020', '2021'
        ];
        editor.jqxDropDownList({
          autoDropDownHeight: true,
          source: list,
          selectedIndex: 0
        });
      },
      cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
        $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
          ? '<p>N/A</p>'
          : defaulthtml
    },
    {
      text: 'Product',
      datafield: 'productname',
      width: 180
    }, {
      text: 'Quantity',
      datafield: 'quantity',
      width: 80,
      cellsalign: 'right'
    }, {
      text: 'Unit Price',
      datafield: 'price',
      width: 90,
      cellsalign: 'right',
      cellsformat: 'c2'
    },
    {
      text: 'Total',
      datafield: 'total',
      width: 100,
      cellsalign: 'right',
      cellsformat: 'c2'
    }
  ]
});

// Addendum for OP's purposes
// Set default year to 2016 if available is checked
$("#jqxgrid").on('cellvaluechanged', function (evt)
{
  let args = evt.args;
  if (args.datafield === 'available' && args.newvalue)
  {
    let rowData = $('#jqxgrid').jqxGrid('getrowdata', args.rowindex);
    if (rowData.yeareligible === 'N')
      return;
      
    $('#jqxgrid').jqxGrid('setcellvalue', args.rowindex, 'yearValue', 2016);
  }
});

$('#jqxbutton').click(function() 
{ 
    
  let rows = $('#jqxgrid').jqxGrid('getrows');
  let selectedRows = rows
let count = selectedRows.filter(x => x.available).length;
console.log("Printing selected rows/count length");
  console.log(count);

    rows.filter(x => x.available)
    .map(x => 
      x.yeareligible === 'N'
        ? Object.assign({}, x, {yearValue : '-1'}) 
        : Object.assign({}, {yearValue : '2016'}, x)
    );
  
  console.log(selectedRows);
  
});
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet" />
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet" />
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />

1

There are 1 answers

8
General Grievance On
  • To show N/A for the year column, you can use a custom cellsrenderer for the yearValue column:

    cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
      $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
        ? '<p>N/A</p>'
        : defaulthtml
    

    The cellsrenderer returns the new raw html you want to display in the cell without overwriting the underlying value. Unfortunately, you cannot return an element or JQuery object, but for simple html, it works OK.

  • To add yearValue : -1 to selectedRows, you can use map() and Object.assign() to return a merged object.

    let rows = $('#jqxgrid').jqxGrid('getrows');
    let selectedRows = rows
      .filter(x => x.available)
      .map(x => 
        x.yeareligible === 'N'
          ? Object.assign({}, x, {yearValue : '-1'}) 
          : x
      );
    

    The API doesn't have a function to override the cell value returned by any of the getter methods. There is a way to override the editor value (geteditorvalue), but that requires that the value be set at least once via the cell's editor, which is not created until the cell is edited for the first time. If that doesn't happen, geteditorvalue will not called, so you'd end up having to write a similar map function in the end anyway.

    Note that this will always add the yearvalue: '-1' whenever yeareligible is 'N', so you may want to put an additional check for yearvalue != null. Or you may want to consider whether adding the value is necessary at all since yeareligible already tells you the information you need.


Putting it all together:

let firstNames = [
  "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", 
  "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
];

let lastNames = [
  "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", 
  "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", 
  "Vileid", "Saylor", "Bjorn", "Nodier"
];

let yearEligible = [
  "Y", "N", "Y", "Y", "Y", "Y", "N", "N", "N", "N", "Y", "N", "N", "N", "Y", "N", "Y", "N"
];

let productNames = [
  "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", 
  "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", 
  "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
];

let priceValues = [
  "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
];

let data = [];
for (let i = 0; i < 10; i++) 
{
  let productindex = Math.floor(Math.random() * productNames.length);
  let price = parseFloat(priceValues[productindex]);
  let quantity = 1 + Math.round(Math.random() * 10);
  let row = {
    firstname : firstNames[Math.floor(Math.random() * firstNames.length)],
    lastname : lastNames[Math.floor(Math.random() * lastNames.length)],
    yeareligible : yearEligible[Math.floor(Math.random() * lastNames.length)],
    productname : productNames[productindex],
    available : !!(i % 2),
    price : price,
    quantity : quantity,
    total : price * quantity
  };
  data.push(row);
}

let source = {
  localdata: data,
  datatype: "array"
};

let dataAdapter = new $.jqx.dataAdapter(source,
{
  loadComplete: function(data) {},
  loadError: function(xhr, status, error) {}
});

$("#jqxgrid").jqxGrid(
{
  theme: 'energyblue',
  width: 500,
  autoheight: true,
  editable: true,
  source: dataAdapter,
  columns: [{
      text: 'Available',
      datafield: 'available',
      width: 100,
      columntype: 'checkbox'
    }, {
      text: 'First Name',
      datafield: 'firstname',
      width: 100
    }, {
      text: 'Last Name',
      datafield: 'lastname',
      width: 100
    }, {
      text: 'Year Eligible',
      datafield: 'yeareligible',
      width: 100
    },
    {
      text: 'Year',
      width: 120,
      datafield: 'yearValue',
      columntype: 'dropdownlist',
      editable: true,
      createeditor: function(row, column, editor) 
      {
        let list = [
          '2010', '2011', '2012', '2013', '2014', '2015', 
          '2016', '2017', '2018', '2019', '2020', '2021'
        ];
        editor.jqxDropDownList({
          autoDropDownHeight: true,
          source: list,
          selectedIndex: 0
        });
      },
      cellsrenderer : (row, columnfield, value, defaulthtml, columnproperties) =>
        $("#jqxgrid").jqxGrid('getrowdata', row).yeareligible === 'N'
          ? '<p>N/A</p>'
          : defaulthtml
    },
    {
      text: 'Product',
      datafield: 'productname',
      width: 180
    }, {
      text: 'Quantity',
      datafield: 'quantity',
      width: 80,
      cellsalign: 'right'
    }, {
      text: 'Unit Price',
      datafield: 'price',
      width: 90,
      cellsalign: 'right',
      cellsformat: 'c2'
    },
    {
      text: 'Total',
      datafield: 'total',
      width: 100,
      cellsalign: 'right',
      cellsformat: 'c2'
    }
  ]
});

// Addendum for OP's purposes
// Set default year to 2016 if available is checked
$("#jqxgrid").on('cellvaluechanged', function (evt)
{
  let args = evt.args;
  if (args.datafield === 'available' && args.newvalue)
  {
    let rowData = $('#jqxgrid').jqxGrid('getrowdata', args.rowindex);
    if (rowData.yeareligible === 'N')
      return;
      
    $('#jqxgrid').jqxGrid('setcellvalue', args.rowindex, 'yearValue', 2016);
  }
});

$('#jqxbutton').click(function() 
{
  let rows = $('#jqxgrid').jqxGrid('getrows');
  let selectedRows = rows
    .filter(x => x.available)
    .map(x => 
      x.yeareligible === 'N'
        ? Object.assign({}, x, {yearValue : '-1'}) 
        : x
    );

  console.log(selectedRows);
});
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet" />
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet" />
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<div id="jqxgrid"></div>
<input type="button" style="margin: 50px;" id="jqxbutton" value="Get rows" />