1

I want to repeat a form element using jquery's .before(); method , so that users of the form can add more ingredients in this case to their recipe.

So far I have come up with this, however I cant use ruby code in a js file

 $('document').ready(function() {
  var ingredient = '<%= f.text_field :ingredients, :class => :ingred %><br>';
   $('#addIngredient').click(function(e) {
    e.preventDefault();
     $(this).before(ingredient);

   })
  });

I have done it using html5 and had it working doing this

   $('document').ready(function() {

            var ingredient = '<input class="ingredients" name="ingredients" type="text" placeholder="Enter Ingredients Here"><br>';
             $('#addingredient').click(function(event) {
               event.preventDefault();
                $(this).before(ingredient);

                 })
               });

Im just having trouble getting this to fit in with my ruby form

at the moment i get this outputted to the page rather than the text field

     <%= f.text_field :ingredients, :class => :ingred %>

Can anyone help? Much appreciated

4
  • Could you show us the actual output of your template - the rendered page's JS code? Commented Nov 2, 2012 at 19:04
  • Seems like you have the code in a JS file right? I guess ruby won't compile it then. You'll most likely have to output that variable in a <script> tag in the page, either globally or in a namespace for it to be parsed then you can use it in your JS file. Commented Nov 2, 2012 at 19:09
  • how would i do that? apologies still learning Commented Nov 2, 2012 at 19:10
  • I'm not experienced with RoR either, but I'm assuming that's how it works as that's the pattern I use for PHP. This is a rather clunky solution but is the only one I can think of. Maybe someone can enlighten us with a better answer. =] Commented Nov 2, 2012 at 19:12

1 Answer 1

1

In Rails, this should be in a file in the views directory in your rails application (e.g. /myrailsapp/app/views/<controllername>) with an extension of .erb.

You can either have the code above wrapped in <script> </script> tags in your view file called <action>.html.erb or in a partial e.g. _beforeaction.js.erb which you can then load into the main <action>.html.erb file using:

<%= render "beforeaction" %> 

(Note: <action> is the action in your rails controller).

You can read the guides here:

http://guides.rubyonrails.org/layouts_and_rendering.html

http://ruby.about.com/od/rails3tutorial/ss/Getting-Started-With-Rails-Views.htm

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.