Snake
Snake

Reputation: 1197

rails submit select options in form

I need to submit a status from the view but I would like to get rid of the submit button and submit the data when I select my status in the view. I have tried with a select tag that does what I want but doesn't send the new status.

To resume : f.select sends the new data but only with a submit button which I would like to get rid of.

Am I forgetting something in my code ?

My controller :

def update_status
    @ticket = Ticket.find(params[:ticket_id])
    if  @ticket.update_attributes(params[:ticket])
      redirect_to tickets_path
    end
  end

My view :

-if current_user.admin?
   div class="field"
  =form_for @ticket, url: ticket_update_status_path(@ticket), method: :get do |f|
     = f.select(:status, options_for_select(@status, @ticket.status) , :class => 'large m-wrap', data: {submit_on_change: true})
     .btn-blue
       = f.submit
-else
  = @ticket.status

Upvotes: 0

Views: 1395

Answers (2)

Yan Foto
Yan Foto

Reputation: 11378

What you do is simply adding a data attribute to your select, so it would look something like this

<select name="ticket[status]" data-submit_on_change="true">
  <option>...</option>
  ...
</select>

obviously adding a data attribute doesn't automagically submits the form! What you need is some piece of JavaScript such as the following (given that you also use jQuery):

$(document).on('change', '[data-submit_on_change=true]', function(event) {
  $(this).closest('form').submit();
});

the on function attaches an event hander to the event change on all elements matching the selector '[data-submit_on_change=true].

Upvotes: 1

FaithoftheFallen
FaithoftheFallen

Reputation: 510

If you include jquery, instead of data: {submit_on_change: true} in your select options, you can use onchange: "$(this).closest('form').submit()".

Upvotes: 0

Related Questions