I am looking for a way to change the options in a rails form.select field through JavaScript based on the selected option for another select field.
The way I was trying to do this before was by using two separate fields with the same object and different sets of options, like so:
<%= form_with(model: my_model) do |form| %>
  <div class="form-floating" id="input">
    <%= form.select :input, ['a', 'b'], { }, class: "form-control" %>
    <%= form.label :input %>
  </div>
  <div class="form-floating" id="output1">
    <%= form.select :output, ['c', 'd'], { }, class: "form-control" %>
    <%= form.label :output %>
  </div>
  <div class="form-floating" id="output2">
    <%= form.select :output, ['e', 'f'], { }, class: "form-control" %>
    <%= form.label :output %>
  </div>
  <script>
    function onChange() {
      var selected = $('#input option:selected').text()
      if (selected == 'a') {
        $('#output1').show()
        $('#output2').hide()
      }
      if (selected == 'b') {
        $('#output1').hide()
        $('#output2').show()
      }
    }
    $('#input').change(onChange)
    $(window).on("turbolinks:load", onChange)
  </script>
  <%= form.submit class: "btn" %>
<% end %>
The problem with this method is that the :output field is created twice and only the last one (with id="output2") is submitted, so I'm now looking for a way to change the select options in the onChange() method for a single output form.select field.
Any help with this issue or an alternative solution would be greatly appreciated, cheers.
 
    