Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render a partial from jquery and haml

The functionality I plan on doing is to insert some form elements depending on a number chosen from a select tag.

I have a select tag called for number_of_passengers, and i plan to dynamically append new passenger fields for the number chosen. Say I select 2 from number_of_passengers, then 2 forms should appear in a fieldset. these forms contain name, age weight etc.

I tried following this:

call a rails function from jquery?

and just converted it to haml-speak but I get errors whenever I use the :javascript tag. Also I don't think I can "escape" the javascript tag once I am in it

:javascript
  $('#number_of_passengers').change(function() {
    var $num_of_passengers = $(this).val();
    for($i=0; $i<$num_of_passengers;$i++) {
      $('.passenger-info ul').append('<%= escape_javascript( render :partial => "new_passenger", :locals => {:booking => @booking }) %>');
    }
  })

also since I am in a form_for, how do I pass the @booking variable to the local? It seems really complicated and I'm planning of doing the dirty way out of just looping 20 times(20 max passengers) then just hide/show them depending on the selected number. But that's too dirty don't you think?

like image 511
corroded Avatar asked Aug 05 '10 15:08

corroded


2 Answers

To get the interpolation working you need to do something like

!= "$('.passenger-info ul').append('#{escape_javascript( render :partial => 'new_passenger', :locals => {:booking => @booking })}');

so simpler said: add the != to the start of the line, and include the string between double quotes.

Your question about the @booking: I suggest you investigate some nested forms examples to make it clearer for you (e.g. this and this railscast).

like image 181
nathanvda Avatar answered Nov 12 '22 14:11

nathanvda


i actually managed to do this by adding:

respond_to do |format|
  format.js { render :partial => "new_passenger" }
end

so even if the request was in js, it will return an html partial. Nifty

like image 3
corroded Avatar answered Nov 12 '22 14:11

corroded