How to use collection select as a button in Rails?

397 Views Asked by At

In my form I have a collection_select to be able to select the name of the articles, my problem is that when I select any article nothing happens

 <%= form_with url: articles_path do |f| %>
   <%= collection_select(:article, :article_id, @articles, :id, :name ) %>
 <% end %>

Of course I would be missing the submit button, but I would like the user to simply select the article name and pass the data to the controller (without having to put a button below collection_select)

I can't find the way, if someone knows about it and can guide me I would be very grateful

Thank you for your time in reading me.

1

There are 1 best solutions below

2
Ngoral On BEST ANSWER

Supposing you have something like this as HTML for your form

<form action="/some_path" method="post">
  <select name="article_id" id="article_id">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
</form>

You should put the following JS (given you do not use any JS libs such as jquery)

const select = document.getElementById('article_id')
select.addEventListener('change', (event) => {
  const XHR = new XMLHttpRequest()
  const form = event.target.parentElement

  XHR.open(form.getAttribute('method'), form.getAttribute('action'))
  XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  XHR.send("article_id=" + encodeURIComponent(event.target.value)
})

You may also want to add an event listener for error and load on XHR to do some processing depending on was your request successful or not