5

Right now I am using:

<%=button_to_function "✓", checkButton(), :class => "buttonGrey"%>

But the javascript function needs something to be passed to it so it can toggle the class( I want the buttons class to be changed upon pressing it) What would I pass as a param to represent the button?

xxyyxx
  • 2,306
  • 3
  • 24
  • 34

5 Answers5

10

Since "button_to_function" is deprecated since Rails 4.0.2, now you can use "button_tag" helper.

Exemple:

<%= button_tag "Do It", type: 'button', onclick: "myFunction()", class: 'btn btn-default' %>

Note: If you use CoffeeScript, declare your function as:

window.myFunction =>
  ...

because in CofeeScript, functions are not global scoped by default.

Fernando Vieira
  • 3,177
  • 29
  • 26
  • 1
    It works. Tiny correction(s) for the button_tag: enter a comma before 'type' and skip the 'do'. – dd_hk Dec 15 '19 at 13:10
5

You can execute javascript directly in the button_to_function.

In your case:

<%= button_to_function "✓", '$(this).toggleClass("buttonGrey buttonGreen");', :class => "buttonGrey" %>

Hope this helps!

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • This is EXACTLY what I was looking for. I kept having a of problems with actually trying to call a function. Thank you! – xxyyxx Nov 08 '12 at 20:12
  • 3
    button_to_function is deprecated (again) in Rails 4. For some reason it has been in and our of Rails a couple times. Details and alternative solution here: http://stackoverflow.com/questions/14324919/status-of-rails-link-to-function-deprecation – Tom Wilson Apr 23 '14 at 23:56
1

Inside checkButton(), you should be able to access this and manipulate it using jQuery or whatever your framework is.

For example, using jquery:

$(this).toggleClass("buttonGrey buttonGreen");
Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
1

Just use straight up jquery.

$(".buttonGrey").on("click", function() {
  // do something
});
Jason Kim
  • 18,102
  • 13
  • 66
  • 105
0

Use the on click event inside the button tag

Robert
  • 10,126
  • 19
  • 78
  • 130