views:

58

answers:

2

I'm new to rails, and was wondering if I should be putting code like the second line inside my view:

<%= text_field_tag 'new_ingredient' %>
<input type=button ID="btnAddIngredient" Value="Add" onclick="addIngredient();" />

or is there a helper I should be using to generate the tag instead? I know about the form and tag helpers, but I don't want this particular button to be a form submission button. It's just a button that manipulates some items via javascript.

I'm guessing I should be using a helper, but I'm still trying to get familiar with the Rails API documentation and can't seem to find what I am looking for.

+2  A: 

you can use button_to_function, like this

button_to_function "Add", :id => "btnAddIngredient", :onclick => "addIngredient();"

hope it helps =)

more details here: http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#M001757

Staelen
+3  A: 

Depending on your approach, it may also be worth noting that putting JS function calls into on-click events is considered bad-form and will be on its way out in Rails 3, I believe. Depending on your JS framework, its better to listen for the click event on the button and act on that.

Running with jQuery, you could do something like this in the view:

<%= button_to "Add", :url => "#", :id => "btnAddIngredient" %>

And this in your application.js or other JS file:

$("#btnAddIngredient").click(function() {
    addIngredient();
});
Kyle Daigle
+1 for unobtrusive javascript.
Matt Briggs
Thanks for the post. If I used button_to instead of button_to_function, then the button actually posts the form, which isn't the behavior I'm looking for here. Thanks for the tip about listening for the button click!
Jeremy Mullin
In theory, you should be able to capture the form submission by doing a "return false;" at the end of the click event function. That way, the form won't submit.
Kyle Daigle