logo
down
shadow

Reset input fields of dynamically generated widgets through insertUI


Reset input fields of dynamically generated widgets through insertUI

By : user3100418
Date : January 12 2021, 07:00 PM
With these it helps I am trying to develop a shinyapp that is part of a bigger form. In particular, for this module the users have the possibility to dynamically add (through insertUI) and remove (through removeUI) a new row with the exact same widgets of the previous one. Moreover, every new widget will contain the exact selected same choices of the widgets of the previous row, credits to Eli Berkow for having found the solution for this last functionality. , See below:
code :
library(shiny)
library(shinyjs)

###= UI
ui <- fluidPage(

    br(),

    useShinyjs(),

    br(),

    fluidRow(
        column(width = 3,
               align = "center",
               h5("Letters")
        ),
        column(width = 3,
               align = "center",
               h5("Numbers")
        )
    ),

    br(),

    fluidRow(
        column(width = 12,
               tags$div(id = "amr_test_placeholder")
        )
    ),

    fluidRow(

        br(),
        # "+" and "-" buttons
        column(width = 12,
               actionButton(inputId = "add_amr_test",
                            label = icon(name = "plus",
                                         lib = "font-awesome")),
               actionButton(inputId = "remove_amr_test",
                            label = icon(name = "times",
                                         lib = "font-awesome")),
               actionButton(inputId = "reset_button",
                            label = "RESET FIELDS")
        )
    ),

    br(),
    br()

)

###= SERVER
server <- function(input, output, session) {

    observe({

        toggleState(id = "remove_amr_test",
                    condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

        toggleState(id = "reset_button",
                condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

    })



    amr_test_values <- reactiveValues(val = 0,
                                      reset = 0)


    ### Defined the input number to count every row
    input_number <- reactive({

        input_number <- input$add_amr_test - input$remove_amr_test - amr_test_values$reset

        return(input_number)

    })




    observeEvent(input$add_amr_test, {

        amr_test_divId <- length(amr_test_values$val) + 1

        ###= Animal species
        if (!is.null(eval(parse(text = paste0("input$letters_", input_number() - 1))))) {

            letters_value = eval(parse(text = paste0("input$letters_", input_number() - 1)))

        } else {

            letters_value = ""

        }

        ###= Animal sample type
        if (!is.null(eval(parse(text = paste0("input$numbers_", input_number() - 1))))) {

            numbers_value = eval(parse(text = paste0("input$numbers_", input_number() - 1)))

        } else {

            numbers_value = ""

        }

        ###= Insert dynamic UI
        insertUI(
            selector = "#amr_test_placeholder",
            where = "beforeBegin",
            ui = tags$div(id = amr_test_divId,
                          tags$head(tags$style(HTML(".shiny-split-layout > div {overflow: visible;}"))),

                          br(),

                          fluidRow(
                              column(width = 3,
                                     splitLayout(cellWidths = c("18%", "82%"),
                                                 h5(paste0(input_number(), ". ")),
                                                 selectizeInput(inputId = paste0("letters_",
                                                                                 input_number()),
                                                                label =  NULL,
                                                                choices = c("A" = "",
                                                                            "A",
                                                                            "B",
                                                                            "C",
                                                                            "D",
                                                                            "E",
                                                                            "F",
                                                                            "F"),
                                                                selected = letters_value,
                                                                width = "100%",
                                                                options = list(create = TRUE))
                                     )
                              ),
                              column(width = 3,
                                     selectizeInput(inputId = paste0("numbers_",
                                                                     input_number()),
                                                    label = NULL,
                                                    choices = list("1" = "",
                                                                   "1" = "1",
                                                                   "2" = "2",
                                                                   "3" = "3",
                                                                   "4" = "4",
                                                                   "5" = "5"),
                                                    selected = numbers_value,
                                                    width = "100%")
                              )
                          )
            )
        )

        amr_test_values$val <- c(amr_test_values$val,
                                 amr_test_divId)

    })

    ###= Remove dynamic UI
    observeEvent(input$remove_amr_test, {

        removeUI(

            selector = paste0('#', amr_test_values$val[length(amr_test_values$val)])

        )

        amr_test_values$val <- amr_test_values$val[-length(amr_test_values$val)]

    })

    observeEvent(input$reset_button, {
        for(remove_value in 2:max(amr_test_values$val)) {
            removeUI(

                selector = paste0('#', remove_value)

            )
        }

        amr_test_values$reset <- input$add_amr_test - input$remove_amr_test
        amr_test_values$val <- 0
    })

}


###= Launch App
shinyApp(ui = ui, server = server)
observe({

    toggleState(id = "remove_amr_test",
                condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

    toggleState(id = "reset_button",
                condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

})



amr_test_values <- reactiveValues(val = 0,
                                  reset = 0)


### Defined the input number to count every row
input_number <- reactive({

    input_number <- input$add_amr_test - input$remove_amr_test - amr_test_values$reset

    return(input_number)

})
observeEvent(input$reset_button, {
    for(remove_value in 2:max(amr_test_values$val)) {
        removeUI(

            selector = paste0('#', remove_value)

        )
    }

    amr_test_values$reset <- input$add_amr_test - input$remove_amr_test
    amr_test_values$val <- 0
})
library(shiny)
library(shinyjs)

###= UI
ui <- fluidPage(

  br(),

  useShinyjs(),

  br(),

  fluidRow(
    column(width = 3,
           align = "center",
           h5("Letters")
    ),
    column(width = 3,
           align = "center",
           h5("Numbers")
    )
  ),

  br(),

  fluidRow(
    column(width = 12,
           tags$div(id = "amr_test_placeholder")
    )
  ),

  fluidRow(

    br(),
    # "+" and "-" buttons
    column(width = 12,
           actionButton(inputId = "add_amr_test",
                        label = icon(name = "plus",
                                     lib = "font-awesome")),
           actionButton(inputId = "remove_amr_test",
                        label = icon(name = "times",
                                     lib = "font-awesome")),
           actionButton(inputId = "reset_button",
                        label = "RESET FIELDS")
    )
  ),

  br(),
  br(),

  fluidRow(
    column(width = 6,
           tableOutput(outputId = "show_table")
    )
  )

)

###= SERVER
server <- function(input, output, session) {

  observe({

    toggleState(id = "remove_amr_test",
                condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

    toggleState(id = "reset_button",
                condition = input$add_amr_test > input$remove_amr_test + amr_test_values$reset)

  })



  amr_test_values <- reactiveValues(val = 0,
                                    reset = 0)


  ### Defined the input number to count every row
  input_number <- reactive({

    input_number <- input$add_amr_test - input$remove_amr_test - amr_test_values$reset + 1

    return(input_number)

  })




  observeEvent(input$add_amr_test, {

    amr_test_divId <- length(amr_test_values$val) + 1

    ###= Animal species
    if (!is.null(eval(parse(text = paste0("input$letters_", input_number() - 1))))) {

      letters_value = eval(parse(text = paste0("input$letters_", input_number() - 1)))

    } else {

      letters_value = "A"

    }

    ###= Animal sample type
    if (!is.null(eval(parse(text = paste0("input$numbers_", input_number() - 1))))) {

      numbers_value = eval(parse(text = paste0("input$numbers_", input_number() - 1)))

    } else {

      numbers_value = 1

    }

    ###= Insert dynamic UI
    insertUI(
      selector = "#amr_test_placeholder",
      where = "beforeBegin",
      ui = tags$div(id = amr_test_divId,
                    tags$head(tags$style(HTML(".shiny-split-layout > div {overflow: visible;}"))),

                    br(),

                    fluidRow(
                      column(width = 3,
                             splitLayout(cellWidths = c("18%", "82%"),
                                         h5(paste0(input_number(), ". ")),
                                         selectizeInput(inputId = paste0("letters_",
                                                                         input_number()),
                                                        label =  NULL,
                                                        choices = c("A" = "",
                                                                    "A",
                                                                    "B",
                                                                    "C",
                                                                    "D",
                                                                    "E",
                                                                    "F",
                                                                    "F"),
                                                        selected = letters_value,
                                                        width = "100%",
                                                        options = list(create = TRUE))
                             )
                      ),
                      column(width = 3,
                             selectizeInput(inputId = paste0("numbers_",
                                                             input_number()),
                                            label = NULL,
                                            choices = list("1" = "",
                                                           "1" = "1",
                                                           "2" = "2",
                                                           "3" = "3",
                                                           "4" = "4",
                                                           "5" = "5"),
                                            selected = numbers_value,
                                            width = "100%")
                      )
                    )
      )
    )

    amr_test_values$val <- c(amr_test_values$val,
                             amr_test_divId)

  }, ignoreNULL = FALSE)

  ###= Remove dynamic UI
  observeEvent(input$remove_amr_test, {

    removeUI(

      selector = paste0('#', amr_test_values$val[length(amr_test_values$val)])

    )

    amr_test_values$val <- amr_test_values$val[-length(amr_test_values$val)]

  })


  observeEvent(input$reset_button, {
    for(remove_value in 3:max(amr_test_values$val)) {
      removeUI(

        selector = paste0('#', remove_value)

      )
    }

    amr_test_values$reset <- input$add_amr_test - input$remove_amr_test
    amr_test_values$val <- c(0, 2)
  })



  ###= Dataset to check the dynamic updates of the responses
  response <- reactive({

    if (input_number() != 0 & !is.null(input[[paste0("letters_", input_number())]])) {

      response <- data.frame("Letters" = sapply(X = 1:input_number(),
                                                FUN = function(i) {

                                                  input[[paste0("letters_", i)]]

                                                }),
                             "Numbers" = sapply(X = 1:input_number(),
                                                FUN = function(i) {

                                                  input[[paste0("numbers_", i)]]

                                                })

      )

      return(response)

    } else {

      response <- NULL

    }

  })



  output$show_table <- renderTable({

    response()

  })

}



###= Launch App
shinyApp(ui = ui, server = server)


Share : facebook icon twitter icon
Set the Value of Dynamically Generated DIV input Fields

Set the Value of Dynamically Generated DIV input Fields


By : Cassandra Hom
Date : March 29 2020, 07:55 AM
With these it helps not sure wheter i got this one right, but it seems you're looking for a way to loop over a jquery collection, which can be done using jQuery.each.
so instead of watching out for some generated IDs on your input field, i'd recommend looping over all of your generated 'fields', itentified by their class editorRow. just note that instead of having a separate id for each input field, you'd have to set some class on them, for example:
code :
<div class="editorRow">
   <!-- set a class on your input fields -->
   Area Code <input class="areaCode" type="text" value="..." />
</div>
$('.editorRow').each(function(){
  var $row = $(this);
  $('.areaCode', $row).val('somevalue');  //do this for all of your input fields
});
Add input fields dynamically but fields are generated by external php functions

Add input fields dynamically but fields are generated by external php functions


By : Sujeet Kumar
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Your function addmore() isn't returning anything because
There is no return "value" in your function You're making an asynchronous call with $jd.ajax()
code :
var counter = 0;
function addInput(divName){
      addmore(divName);
}
function addmore(divName){
        $jd.ajax({
          url: "<?php echo JURI::root(); ?>",
          type: "POST",
          data: {'option':'com_joomd', 'view':'itempanel', 'task':'loadfields', 'typeid':<?php echo $this->cparams->typeid; ?>, 'catid[]':checked, 'id':<?php echo (int)$this->item-        id; ?>, "<?php echo jutility::getToken(); ?>":1, 'abase':1},
          beforeSend: function()    {
            $jd(".poploadingbox").show();
          },
          complete: function()  {
            $jd(".poploadingbox").hide();
          },
          success: function(res)    {
             var newdiv = document.createElement('div');
             newdiv.innerHTML = "Member " + (counter + 1) + res;
             document.getElementById(divName).appendChild(newdiv);
             counter++;

          },
          error: function() {
              alert('error');                 
          }
    });
}
Save dynamically generated input fields

Save dynamically generated input fields


By : chaturbhuj
Date : March 29 2020, 07:55 AM
Does that help One approach is to define a template to add it dynamically via jQuery
Template
code :
<script type="text/html" id="form_tpl">
  <div class = "control-group" > 
    <label class = "control-label"for = 'emp_name' > Employer Name </label>
    <div class="controls">
        <input type="text" name="work_emp_name[<%= element.i %>]" class="work_emp_name"
               value="" /> 
    </div>
</div>
$("form").on("click", ".add_employer", function (e) {
   e.preventDefault();
   var tplData = {
      i: counter
   };
   $("#word_exp_area").append(tpl(tplData));
  counter += 1;
});
JQuery for dynamically generated input fields

JQuery for dynamically generated input fields


By : Saravana Priyan
Date : March 29 2020, 07:55 AM
hope this fix your issue I am having a problem with the following; I have a dynamically generated table form. In one of the columns I have a select input with some options and in the following column I have an input field for Timestamp that should be automatically filled out with the current date as soon as the user selects one of the options. I have the following code, however, the timestamp is either only generated for the very first row (in case when I use id for input field) or for all of the rows (in case when I use class for input field). I would need the timestamp to be filled only in the same row as the select drop down list is. Any help would be greatly appreciated. , Try this:
code :
$(document).ready(function() {
    $('.Status').on('change', function() {
        // get current row
        var row = $(this).parent().parent();
        // find .TimeStanp in the current row and set value
        row.find('.TimeStamp').val("CurrentDate");         
    });
});
Adding and removing dynamically generated QLineEdit widgets based off of user input from a QComboBox

Adding and removing dynamically generated QLineEdit widgets based off of user input from a QComboBox


By : user2428069
Date : March 29 2020, 07:55 AM
like below fixes the issue If you want to remove a widget from a layout you just have to use deleteLater but that does not mean that the references will be deleted if they are stored in a list. In my strategy I eliminate all the QLineEdits with deleteLater, I reset the list that stored it and I create the new QLineEdits.
code :
from PySide2 import QtCore, QtWidgets

class RollMultiDiePopup(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(RollMultiDiePopup, self).__init__(parent)

        self._data = {
            "D4": 4, 
            "D6": 6, 
            "D8": 8, 
            "D10": 10, 
            "D12": 12, 
            "D20": 20
        }

        self._lineedits = [[] for _ in self._data]
        self._comboboxes = []

        grid_layout = QtWidgets.QGridLayout(self)
        self.create_labels()
        self.create_comboboxes()
        self.create_buttons()

    def create_labels(self):
        row = 0
        grid_layout = self.layout()
        for i, k in enumerate(self._data.keys()):
            label = QtWidgets.QLabel("# of {}s".format(k))
            grid_layout.addWidget(label, row, i)

    def create_comboboxes(self):
        row = 1
        grid_layout = self.layout()
        for i in range(len(self._data)):
            combo = QtWidgets.QComboBox()
            combo.addItems([str(j) for j in range(21)])
            self._comboboxes.append(combo)
            grid_layout.addWidget(combo, row, i)

    def create_buttons(self):
        row = 2
        grid_layout = self.layout()
        for i, (k, v) in enumerate(self._data.items()):
            button = QtWidgets.QPushButton("Roll {}s".format(k))
            button.setToolTip("Roll {}(1 - {})".format(k, v))
            button.clicked.connect(self.update_lineedits)
            grid_layout.addWidget(button, row, i)

    @QtCore.Slot()
    def update_lineedits(self):
        row = 3
        grid_layout = self.layout()
        for r in self._lineedits:
            for le in r:
                le.deleteLater()
        self._lineedits = [[] for _ in self._data]
        for i, (les,combo) in enumerate(zip(self._lineedits, self._comboboxes)):
            v = int(combo.currentText())
            for j in range(v):
                le = QtWidgets.QLineEdit()
                le.setPlaceholderText("Die Roll #{}".format(j+1))
                grid_layout.addWidget(le, row+j, i)
                les.append(le)
        QtCore.QTimer.singleShot(0, self.adjust_size)

    @QtCore.Slot()
    def adjust_size(self):
        animation = QtCore.QPropertyAnimation(self, b"size", self)
        animation.setStartValue(self.size())
        animation.setEndValue(self.minimumSizeHint())
        animation.start(QtCore.QAbstractAnimation.DeleteWhenStopped)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = RollMultiDiePopup()
    w.show()
    sys.exit(app.exec_())
Related Posts Related Posts :
  • How to retrieve the data frame used in a GEE model fit?
  • R: How to find/replace and then automatically execute code?
  • Slope of time series (xts) object over rolling window
  • Is there an R function for comparing rows in data.frame?
  • Changing linetype and line color with plot_model()
  • Update existing package on CRAN
  • Delete NA data ,but with certain condition in R
  • calculate number and names of similar sounding words from a data frame
  • Select certain region of column for lm
  • Convert multiple rows into one row depending on unique values in another column
  • Issues installing Plotly Dash for R
  • Is there an R function to retrieve values from a matrix of column names?
  • R;Too slow to overate loops for million vectors
  • How to optimize intersect of rows and columns in a matrix?
  • Format and export the output of Mann-Kendall test in R to excel from Rstudio
  • how to calculate cumsum with depreciation in a grouped dataframe?
  • reshape wide to long based on part of column name
  • How to get a hyperlink for the words in a description in an r dataframe?
  • shinymeta works locally but breaks when published to shinyapps.io
  • Deparse and (un)escape quotes
  • Regression table with clustered standard errors in R jupyter notebook?
  • Disaggregate quarterly data to daily data in R keeping values?
  • How to save output to console and file simultaneously in RStudio server?
  • Why does data.table j have a different environment when directly calling mget() vs calling mget() inside another functio
  • scale_fill_viridis_c color bar on a log scale
  • How to change the lab name corresponding to function in ggplot
  • R, filtering for an element in a list in a dataframe cell
  • Extracting only bottom temperature from 4d NetCDF file
  • How to add/wrap lines of text to .tex with .sh script
  • R - building new variables from sequenced data
  • Sum rows values one after the other
  • Nesting ifelse inside summarytools
  • How best to divide different levels of a factor by one another in dataframe in R?
  • Why does my code run multiple times before I type data into the table? How do I make an action button that creates a tab
  • How to impute missing values not at random?
  • Set the y limits of an added average line of a plotly plot
  • how to calculate a new column after grouping with dplyr
  • Extract data from rows creating new columns using R
  • Create a filled area line plot with plotly
  • When do I need parentheses around an if statement to control the sequence of a formula in R?
  • my graph in ggplot2 contains an "e" character in y-axis
  • Making variables immutable in R
  • R: Difference between the subsequent ranks of a item group by date
  • Match data within multiple time-frames with dplyr
  • Conditional manipulation and extension of rows in data.table also considering previous extensions without for-loop
  • Conditional formula referring to preview row in DF not working
  • Set hoverinfo text in plotly scatterplot
  • Histogram of Sums from Categorical/Binary Data
  • Efficiently find set differences and generate random sample
  • Find closest points from data set B to point in data set A, using lat long in R
  • dplyr join on column A OR column B
  • Replace all string if row starts with (within a column)
  • Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?
  • How can I extract bounding boxes in a row-wise manner using R?
  • How do I easily sum up values in different columns?
  • How to identify all columns that contain binary representation
  • Filter different groups by different factor levels
  • Saving .xlsx file to disc, form http post request
  • Add an "all" option under the filter that selects the number of rows displayed in a datatable
  • How to select second column of every xts in list
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org