Boxuan
Boxuan

Reputation: 5157

R shiny selectInput(): multiple option groups not working with one option

I am trying to make option groups in selectInput(), but seeing the following unexpected result.

If you type the following line in your console:

selectInput("test", "I am test", choices = list("Group A" = c("a", "b", "c"), "Group B" = "d"))

You should see the following output:

<div class="form-group shiny-input-container">
   <label class="control-label" for="test">I am test</label>
   <div>
      <select id="test">
         <optgroup label="Group A">
            <option value="a" selected>a</option>
            <option value="b">b</option>
            <option value="c">c</option>
         </optgroup>
         <option value="d">Group B</option>       <====== wrong
      </select>
      <script type="application/json" data-for="test" data-nonempty="">{}</script>
   </div>
</div>

The problem with the above code is, the Group B should be the optgroup label instead of option text. I imagine the above code should return the following:

<div class="form-group shiny-input-container">
   <label class="control-label" for="test">I am test</label>
   <div>
      <select id="test">
         <optgroup label="Group A">
            <option value="a" selected>a</option>
            <option value="b">b</option>
            <option value="c">c</option>
         </optgroup>
         <optgroup label="Group B">            <====== correct
            <option value="d">d</option>       <====== correct
         </optgroup>                           <====== correct
      </select>
      <script type="application/json" data-for="test" data-nonempty="">{}</script>
   </div>
</div>

Is this expected? If not, how could I fix it?

Upvotes: 1

Views: 1703

Answers (1)

NicE
NicE

Reputation: 21425

You can put your Group B choice in a list to get the output you want:

selectInput("test", "I am test", choices = list("Group A" = c("a", "b", "c"), "Group B" = list("d")))

Upvotes: 2

Related Questions