Home > Net >  select2 was not applied to all dropdowns; it only applied to the last record of data
select2 was not applied to all dropdowns; it only applied to the last record of data

Time:01-12

In one of my applications, I want to update the data when someone changes the value in a dropdown. I did that thing with turbo_stream. I have a lot of values in my dropdown, and I'd like to search through them as well. Hence, I am using the select2 rails gem. But when I applied select2, then I was facing some issues, like select2 being applied to only the last dropdown item. If I have ten data, it skips the first nine and only applies to the last dropdown.

Note : Update functionality with turbo_stream is working fine.

Working Configuration :

  • rails - 7.0.4
  • ruby - 3.1.2

Here I am adding dropdown code in which I changed the value using turbo_stream,

Before Adding select2,

<div data-controller="devdropdownbox">
  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary" %>
</div>

After Adding select2

To apply select2, I have added an autosuggest class to the dropdown and written some JavaScript code.

<div data-controller="devdropdownbox">
  <%= f.select :status, Developer.developer_stauses(developer.id).map {|key, value| [key.humanize, value]}, data: { action: 'change->dropdownvalues#changeDeveloperStatus', turbo_frame: :assign_interview_modal}, class: "bg-primary autosuggest" %>
</div>

JavaScript for autosuggest,

<script>
  $(document).ready(function() {
    $('.autosuggest').select2({
    });
  });
</script>

Javascript is executed when the page DOM is ready.

So, after adding this, all of the values continue to update properly, but as I previously stated, select2 is only applied to the last set of data. I also added some styling.

I am attaching a screenshot of the problem to explain it in a better way

Screenshot of problem :
enter image description here

CodePudding user response:

This kind of problem recently came up in my rails project. By using the html select tag rather of the rails f.select drop-down, I was able to solve this problem. You can utilise a standard HTML drop-down.

Here, I substituted a chunk of HTML code for the stimulus rails code.

Try with this code:

<div data-controller="devdropdownbox">
  <select  data-action="change->dropdownvalues#changeDeveloperStatus" data-turbo-frame="assign_interview_modal" >
    <% Developer.developer_stauses(developer.id).each do |key, value| %>
      <option value="<%= value %>"><%= key %></option>
    <% end %>
  </select>
</div>
  • Related