0

I have another JavaScript question. I use a DataTable with the keyTable extension. This extension marks a single cell and you can navigate through the table with the arrow keys.

I want to read out, what cell is selected anytime. I think the easiest way is to do it with JavaScript, but I am an absolute beginner with JS, so you have to help me.

Code like

"table.on('key', function(e, datatable, key, cell, originalEvent){",
"  var targetName = originalEvent.target.localName;",
"  if(key == 13 && targetName == 'body'){",
"      Shiny.setInputValue('Ausgaben_zelle_aenderung', cell.node());",
"  }",
"});",
"table.on('key-focus', function(e, datatable, cell, originalEvent){",
"  var targetName = originalEvent.target.localName;",
"  var type = originalEvent.type;",
"  if(type == 'keydown' && targetName == 'input'){",
"    if([9,13,37,38,39,40].indexOf(originalEvent.keyCode) > -1){",
"      Shiny.setInputValue('Ausgaben_zelle_aenderung', cell.node());",
"    }",
"  }",
"});"

gives me the information what cell is selected, while I'm in the editing mode. This works. I want to modify this code to get the cell information when I don't change the value. So I tried to adapt the code, but code like

"table.on('key', function(e, datatable, key, cell, originalEvent){",
"  if([9,13,37,38,39,40].indexOf(key) > -1){",
"      Shiny.setInputValue('test1', cell.node());",
"  }",
"});"

is not working. Can you help me?

With best regards Chefkoch

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
Chefkoch
  • 27
  • 5
  • 1
    If I correctly understand what you want, I would try to remove `&& targetName == 'input'` in the `key-focus` event handler. (You should always provide a minimal reproducible example, so that someone who wants to help you can give a try). – Stéphane Laurent Dec 26 '20 at 20:35
  • it could be so easy! Thank you very much, again! – Chefkoch Dec 26 '20 at 20:43

1 Answers1

1

In this code:

"table.on('key-focus', function(e, datatable, cell, originalEvent){",
"  var targetName = originalEvent.target.localName;",
"  var type = originalEvent.type;",
"  if(type == 'keydown' && targetName == 'input'){",
"    if([9,13,37,38,39,40].indexOf(originalEvent.keyCode) > -1){",
"      Shiny.setInputValue('Ausgaben_zelle_aenderung', cell.node());",
"    }",
"  }",
"});"

targetName is the type of the element in which the key has been pressed. It is an input when you are in editable mode. So, if you want always to get the cell info, remove the targetName == 'input' test:

"table.on('key-focus', function(e, datatable, cell, originalEvent){",
"  var type = originalEvent.type;",
"  if(type == 'keydown'){",
"    if([9,13,37,38,39,40].indexOf(originalEvent.keyCode) > -1){",
"      Shiny.setInputValue('Ausgaben_zelle_aenderung', cell.node());",
"    }",
"  }",
"});"
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225