Javascript 如何在更新的UI中格式化数字输入?
下面的工作示例源自我前面的问题。现在我想用逗号格式化Javascript 如何在更新的UI中格式化数字输入?,javascript,r,shiny,format,shiny-reactivity,Javascript,R,Shiny,Format,Shiny Reactivity,下面的工作示例源自我前面的问题。现在我想用逗号格式化numericInput字段,以帮助用户读取大量数字。我遵循了本文“”中选项2的示例,用这种样式更改了总计数值输入。关键是创建一个.js文件,对数字进行格式化,并将其存储在www目录下,与脚本位于同一文件夹下 这与TotalnumericInput配合得很好。但是,对于那些更新后添加的数值输入,如何使用相同的格式?挑战在于我无法知道以后会添加多少numericInput,因此如果我不知道要添加到该文件的inpur ID,则很难修改格式的\u n
numericInput
字段,以帮助用户读取大量数字。我遵循了本文“”中选项2的示例,用这种样式更改了总计数值输入。关键是创建一个.js
文件,对数字进行格式化,并将其存储在www
目录下,与脚本位于同一文件夹下
这与Total
numericInput配合得很好。但是,对于那些更新后添加的数值输入
,如何使用相同的格式?挑战在于我无法知道以后会添加多少numericInput
,因此如果我不知道要添加到该文件的inpur ID,则很难修改格式的\u numbers.js
文件
格式_numbers.js
如下所示
$(document).ready(function() {
// Helper function to guarantee cross-browser compatibility
// adapted from: http://stackoverflow.com/a/16157942
function localeString(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default separator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
// To change Total's input field (lose arrows and other functionality)
$('#Total')[0].type = 'text';
// To format the number when the app starts up
$('#Total').val(localeString($('#Total').val()));
// To format the number whenever the input changes
$('#Total').keyup(function(event) {
$(this).val(localeString($(this).val().replace(/,/g, '')));
});
});
library(shiny)
# Define UI
ui <- fluidPage(
# Modify tags
tags$head(tags$script(src = "format_numbers.js")),
# Action button to add numeric input
actionButton("add", "Add UI"),
actionButton("sum", "Sum"),
# Numeric Input
numericInput(inputId = "Total", label = "Total", value = 0),
# Text output
"The number is ",
textOutput(outputId = "out_num", inline = TRUE)
)
# Server logic
server <- function(input, output, session){
# Add numeric input
observeEvent(input$add, {
insertUI(
selector = "#add",
where = "afterEnd",
ui = numericInput(paste0("txt", input$add), label = "Number", value = 0)
)
})
# Reactive values for Total
Num_In <- reactiveValues(
Total_In = 0
)
# Convert number to character
# This is to fill in the Total numeric input formatting with comma
total_num_as_char <- reactive({format(Num_In$Total_In, big.mark = ",", trim = TRUE)})
total_input <- reactive({Num_In$Total_In})
observeEvent(input$sum, {
num_names <- names(input)[grepl("^txt", names(input))]
if (length(num_names) == 0) {
foo <- 0
} else {
foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
}
Num_In$Total_In <- foo
updateNumericInput(session = session,
inputId = "Total",
value = total_num_as_char())
})
# Convert input to numeric
total_num <- reactive({as.numeric(gsub(",", "", input$Total))})
# Create text output
output$out_num <- renderText({total_num()})
}
# Complete app with UI and server components
shinyApp(ui, server)
闪亮的脚本如下
$(document).ready(function() {
// Helper function to guarantee cross-browser compatibility
// adapted from: http://stackoverflow.com/a/16157942
function localeString(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default separator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
// To change Total's input field (lose arrows and other functionality)
$('#Total')[0].type = 'text';
// To format the number when the app starts up
$('#Total').val(localeString($('#Total').val()));
// To format the number whenever the input changes
$('#Total').keyup(function(event) {
$(this).val(localeString($(this).val().replace(/,/g, '')));
});
});
library(shiny)
# Define UI
ui <- fluidPage(
# Modify tags
tags$head(tags$script(src = "format_numbers.js")),
# Action button to add numeric input
actionButton("add", "Add UI"),
actionButton("sum", "Sum"),
# Numeric Input
numericInput(inputId = "Total", label = "Total", value = 0),
# Text output
"The number is ",
textOutput(outputId = "out_num", inline = TRUE)
)
# Server logic
server <- function(input, output, session){
# Add numeric input
observeEvent(input$add, {
insertUI(
selector = "#add",
where = "afterEnd",
ui = numericInput(paste0("txt", input$add), label = "Number", value = 0)
)
})
# Reactive values for Total
Num_In <- reactiveValues(
Total_In = 0
)
# Convert number to character
# This is to fill in the Total numeric input formatting with comma
total_num_as_char <- reactive({format(Num_In$Total_In, big.mark = ",", trim = TRUE)})
total_input <- reactive({Num_In$Total_In})
observeEvent(input$sum, {
num_names <- names(input)[grepl("^txt", names(input))]
if (length(num_names) == 0) {
foo <- 0
} else {
foo <- sum(sapply(num_names, function(x) input[[x]]), na.rm = TRUE)
}
Num_In$Total_In <- foo
updateNumericInput(session = session,
inputId = "Total",
value = total_num_as_char())
})
# Convert input to numeric
total_num <- reactive({as.numeric(gsub(",", "", input$Total))})
# Create text output
output$out_num <- renderText({total_num()})
}
# Complete app with UI and server components
shinyApp(ui, server)
库(闪亮)
#定义用户界面
ui对我来说,以下是有效的
当使用insertUI
添加UI组件时,会触发JS事件shinny:bound
。然后我们可以利用这一点:
//保证跨浏览器兼容性的助手函数
//改编自:http://stackoverflow.com/a/16157942
功能本地限制(x、sep、grp){
变量sx=(''+x).分割('.'),s='',i,j;
sep | |(sep=',');//默认分隔符
grp | | grp==0 | |(grp=3);//默认分组
i=sx[0]。长度;
而(i>grp){
j=i-grp;
s=sep+sx[0],切片(j,i)+s;
i=j;
}
s=sx[0]。切片(0,i)+s;
sx[0]=s;
返回sx.join('.');
}
$(文档).ready(函数(){
//更改Total的输入字段(丢失箭头和其他功能)
$('#Total')[0]。类型='text';
//在应用程序启动时设置号码格式
$('Total').val(localeString($('Total').val());
//在输入更改时设置数字格式的步骤
$(“#总计”).keyup(函数(事件){
$(this.val)(localeString($(this.val().replace(/,/g,)));
});
});
$(文档).on('shiny:bind',函数(evt){
var id=evt.target.getAttribute('id');
如果(/^(txt)/).test(id)){
变量选择器=“#”+id;
$(选择器)[0]。类型='text';
$(选择器).val(localeString($(选择器).val());
$(选择器).keyup(函数(事件){
$(this.val)(localeString($(this.val().replace(/,/g,)));
});
}
});
现在,在R中:
unformat <- function(x) as.numeric(gsub(",", "", x))
谢谢你的帮助。这个解决方案看起来很有希望。我对你的答案投了赞成票。在使用更新更改js
和R脚本后,添加的数字输入字段仍然显示数字,但不带逗号。您能检查一下这个解决方案在您的机器上是否还能正常工作吗?@www.worden。我又检查了一遍,是的,这是有效的。例如,1111
自动更改为1111
。我同意它应该可以工作。我觉得我的代码与您的解决方案相同。唯一的区别可能是unformat
函数的位置,但这并不重要。我编辑了我的帖子,并把js
和放在闪闪发光的代码中。如果你不介意的话,你能检查一下你的机器上的代码是否正常吗?非常感谢。@www您是否尝试将函数localeString
放在$(文档)之外。准备好了(function(){……})
?否则,我不确定它是否在$(文档)中定义。在('shinny:bound',…
。它可以工作。正如您所说,我的js
脚本不正确。非常感谢您对此进行研究。