Vibrant DT data table featuring vertical radio buttons

I am in need of a polished DT datatable that includes radio buttons embedded within a column. While this application provides a solution for horizontal buttons, I have taken on the task of adapting it for a vertical layout. Modifying the matrix was a straightforward process (refer to the code below), but I find myself stuck at the callback section due to my limited knowledge of JavaScript. Any suggestions or insights would be greatly appreciated.

UPDATE: Unless radio buttons are mandatory, utilizing the row selection feature in DT and setting the selection attribute to "single" may offer a simpler alternative, allowing only one row to be selected.

library(shiny)
library(DT)
m = matrix(
  as.character(1:12), nrow = 12, ncol = 5, byrow = FALSE,
  dimnames = list(month.abb, LETTERS[1:5])
)

for (i in seq_len(ncol(m))) {
  m[, i] = sprintf(
    '<input type="radio" name="%s" value="%s"/>',
    LETTERS[i], m[, i]
  )
}

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
  ),
  server = function(input, output, session) {
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE),
      callback = JS("table.rows().every(function(i, tab, row) {
                    var $this = $(this.node());
                    $this.attr('id', this.data()[0]);
                    $this.addClass('shiny-input-radiogroup');
  });
                    Shiny.unbindAll(table.table().node());
                    Shiny.bindAll(table.table().node());")
    )
    output$sel = renderPrint({
      input[["A"]]
    })
    }
)

Answer №1

import library(shiny)
import library(DT)

matrix_data = matrix(
  as.character(1:12), nrow = 12, ncol = 5, byrow = FALSE,
  dimnames = list(month.abb, LETTERS[1:5])
)
for (index in seq_len(ncol(matrix_data))) {
  matrix_data[, index] = sprintf(
    '<input type="radio" name="%s" value="%s"/>',
    LETTERS[index], matrix_data[,index]
  )
}

callback_function <- c(
  "var LETTERS = ['A','B','C','D','E'];",
  "for(var i=0; i < LETTERS.length; ++i){",
  "  var L = LETTERS[i];",
  "  $('input[name=' + L + ']').on('click', function(){",
  "    var name = $(this).attr('name');",
  "    var value = $('input[name=' + name + ']:checked').val();",
  "    Shiny.setInputValue(name, value);",
  "  });",
  "}"
)

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('table_output'),
    verbatimTextOutput('selected_value')
  ),
  server = function(input, output, session) {
    output$table_output = DT::renderDataTable(
      matrix_data, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 't', paging = FALSE, ordering = FALSE),
      callback = JS(callback_function)
    )
    output$selected_value = renderPrint({
      input[["A"]]
    })
  }
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

Deciphering the time in AM/PM notation

Trying to work with Date-time in AM/PM format in R has been a bit challenging for me. I discovered that using '%p' should help in handling this issue. However, I encountered some discrepancies when attempting the following: mydate <- as.POSIX ...

The AudioPlayerStatus module in Discord JS is a powerful tool for managing

Could you explain why this code snippet: client.player.once(AudioPlayerStatus.Idle, () => { console.log(client.playlist); next.run(message, args, client); client.playlist.shift(); return; }); is b ...

Sending a value to a function using variables in R

Looking for a solution to work with a dataframe in R by passing a column into a variable and then using it in a mean function? library(dplyr) vec1 = 1:10 vec2 = 11:20 df = data.frame(col1 = vec1, col2 = vec2) var = df$col1 x <- df %>% summarize( ...

Having trouble receiving JSON/JSONP correctly

I've been exploring the world of APIs and I'm facing a roadblock right at the beginning. My goal is to extract data from the Fever Public API in order to retrieve a list of subscribed RSS feeds. The API appears to be straightforward - check it ou ...

The module 'safe-buffer' is not found by NPM

Ever since installing yarn, I've been unable to use npm. The upgrade for NodeJS went smoothly. Trying to remove npm is proving impossible. Every command I attempt results in the same error message: module.js:487 throw err; ^ Error: Cannot f ...

Tips on retrieving and refreshing dynamically generated PHP file echo output within a div

I have a div that I'm refreshing using jQuery every 10 seconds. The content is being read from a PHP file named status.php. Here is the JavaScript and HTML for the div: <script> function autoRefresh_div() { $("#ReloadThis").load("status.php ...

inadequate document object module problem

Upon loading a page, I perform some JQuery actions on it. However, when trying to execute the line: var div = $("<div class='modal'>").append(r); I encountered an error mentioning a Hierarchy issue. It made me question if there is imprope ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...

Creating a mapping in a data.table using information from another data.table

In my possession are two sets of data in Excel format, referred to as DT1 and DT2. I am looking to add a new column called 'newcol' to DT1 based on the original columns in DT1, mapping with corresponding columns in DT2. Recognizing that this re ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

Use jQuery to drag an element and display controls in a designated area

I am trying to develop a tool that allows me to drag an image from one section to another, and upon dropping it, the following actions should take place: 1 - The dragged image should revert back to its original position 2 - A set of controls should be add ...

Are there any security risks in transmitting a password over HTTPS using jsonp?

Is it secure to send a password in JSONP using jquery over HTTPS for authentication if I can't use a JSON POST? EDIT: $.ajax({ type : "POST", url: "https://example.com/api.php", dataType: "jsonp", jsonp: "callback", data: { ...

What steps can I take to optimize my code and eliminate any redundancies?

In a current project, I need to make calls to three different endpoints. The functions handling these requests are identical except for the URLs being called. Below is an example of the code: const handleSubmitRequest = (e, next, endpoint, requestData) =&g ...

Error: jQuery Validation not triggering in Bootstrap modal window

My attempts to use jQuery Validation for form validation inside a modal have hit a dead end. The validation doesn't trigger at all, not even an error message is displayed. Upon debugging, a warning emerged: No elements selected for validation; retu ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...

I am having trouble with an undefined variable in my expressjs server.js file. How can I properly reference

When setting up ExpressJS, I have a file named server.js where the following code is executed: import { call_method } from '../hereIam.mjs'; const process_db = async () => { console.log(this); // undefined call_method(this); }; console. ...

EaselJS BitmapAnimation has delay when using gotoAndPlay

I have created a requirejs module that enhances the functionality of a BitmapAnimation by allowing it to move around the stage at a specific speed and transition to another looped animation once reaching its destination. The issue I am encountering is a n ...

An interesting approach to utilizing toggle functionality in JQuery is by incorporating a feature that automatically closes the div when

Currently, I am utilizing JQuery's toggle function to slide a ul li element. However, my desired functionality is for the div to close if someone clicks outside of it (anywhere on the page) while it is in the toggle Down condition. Below, you'll ...

Retrieve the JSON data from an AJAX request

I am a beginner in the world of AJAX and JavaScript. In one of my projects, I need to retrieve a JSON object in my JavaScript file. I have utilized spray-json library which displays the JSON object at this URL: http://localhost:8081/all-modules { "statu ...