You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Shiny中让selectInput的第一个选项显示为粗体

Solution to Make First Option Bold in Shiny selectInput

There are a couple of straightforward ways to achieve this in Shiny. Here are two common approaches:

Method 1: Using JavaScript (Simplest for Existing selectInput)

You can add a small JavaScript snippet to your UI that targets the first option of your selectInput and applies bold styling. This works because Shiny includes jQuery by default, making it easy to manipulate DOM elements:

ui <- fluidPage(
  selectInput( 
    "select", 
    label = h3("Select box"), 
    choices = c(1,2,3,4) 
  ),
  # Add this script to make the first option bold
  tags$script(HTML("
    $(document).ready(function() {
      // Target the first option in the select with id 'select'
      $('#select option:first').css('font-weight', 'bold');
    });
  "))
)

server <- function(input, output) { }

shinyApp(ui = ui, server = server)

This script runs once the page is fully loaded, finds the first <option> element inside your selectInput, and sets its font weight to bold.

Method 2: Build the Select Element Manually with HTML

If you prefer to avoid JavaScript, you can construct the select element using Shiny's HTML tags, allowing you to directly apply bold formatting to the first option:

ui <- fluidPage(
  # Keep the label consistent with your original code
  tags$label(h3("Select box"), `for` = "select"),
  # Manually create the select element with styled options
  tags$select(
    id = "select",
    tags$option(value = 1, HTML("<b>1</b>")),
    tags$option(value = 2, "2"),
    tags$option(value = 3, "3"),
    tags$option(value = 4, "4")
  )
)

server <- function(input, output) { }

shinyApp(ui = ui, server = server)

Here, we use HTML("<b>1</b>") to render the first option's text as bold HTML. This method gives you full control over the HTML structure of the select element.

Both methods will result in the first option ("1") appearing bold in your Shiny app. The JavaScript method is often preferable if you want to keep using the standard selectInput function without modifying how you define your choices.

内容的提问来源于stack exchange,提问作者Adam Shaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:53:04