Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onchange remote_function in rails 3 - is it valid? how can I accomplish it unobtrusively?

I have two questions.

I have a select tag in a rails 3 application that looks like this:

 <%= select(@adverse_event_template_settings, 
    "display_arms", 
    options_for_select([["Yes", true], ["No", false]]), 
    { :selected => :display_arms },  
    :onchange => remote_function(:update => "display_arms", 
          :method => "put", 
          :with => "'display_arms=' + value", 
          :url => { :controller => :adverse_event_template_settings, 
               :action => :update, :id => @aets.id})) %>

This does what I want it to do- that is, call a controller action when the select box value changes.

Even though this works, I want to know 1) Is this valid in rails 3? I know it is obtrusive javascript, but remote_function working in rails 3 seems weird to me - is something wrong here?

and if the above is NOT valid, I really really really would like to know 2) how can I accomplish this same action (i.e. call the same action in the same controller) unobtrusively? Is there a way to do this simply and cleanly in rails 3? I desperately need coding help with this part.

Thank you so much! Let me know if you need more details.

like image 490
Sarah Avatar asked Jan 19 '11 19:01

Sarah


1 Answers

(I assume you are using jQuery).

I would put the javascript part in a .js file and manage the onchange event with jQuery.

<%= select(@adverse_event_template_settings, 
    "display_arms", 
    options_for_select([["Yes", true], ["No", false]]), 
    { :selected => :display_arms }) %>

and in the js file:

  $(document).ready(function() {

    $('#display_arms').change(function(){
      $.ajax({url: 'YOUR URL',
        data: 'display_arms=' + value,
        success: function(data){
          $('#display_arms').html(data);
          }
      })
    });
  });

(I haven't had time to test this but you get the idea)

To be honest, I'm not sure there's a way to do this kind of thing unobtrusively (or I'm interested!).

like image 144
Pierre Avatar answered Nov 18 '22 09:11

Pierre