xxyyxx
xxyyxx

Reputation: 2396

How do I call a javascript function when a button is clicked?

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?

Upvotes: 5

Views: 16674

Answers (5)

Fernando Vieira
Fernando Vieira

Reputation: 3333

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.

Upvotes: 10

Robert
Robert

Reputation: 10390

Use the on click event inside the button tag

Upvotes: 0

MrYoshiji
MrYoshiji

Reputation: 54882

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!

Upvotes: 5

Jason Kim
Jason Kim

Reputation: 19041

Just use straight up jquery.

$(".buttonGrey").on("click", function() {
  // do something
});

Upvotes: 1

Anthony Alberto
Anthony Alberto

Reputation: 10395

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");

Upvotes: 1

Related Questions