How do I call a javascript function when a button

2020-07-17 07:50发布

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?

5条回答
劳资没心,怎么记你
2楼-- · 2020-07-17 08:08

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.

查看更多
【Aperson】
3楼-- · 2020-07-17 08:10

Just use straight up jquery.

$(".buttonGrey").on("click", function() {
  // do something
});
查看更多
做自己的国王
4楼-- · 2020-07-17 08:12

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");
查看更多
\"骚年 ilove
5楼-- · 2020-07-17 08:20

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!

查看更多
淡お忘
6楼-- · 2020-07-17 08:24

Use the on click event inside the button tag

查看更多
登录 后发表回答