Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 408
xxyyxx Avatar asked Nov 08 '12 19:11

xxyyxx


People also ask

How do you run a JavaScript function when a button is pressed?

To call a JavaScript function from a button click, you need to add an event handler and listen for the click event from your <button> element. You can the id attribute to the <button> so that you can fetch it using the document. getElementById() method.

How do you call a function when a link is clicked?

Use the onclick HTML attribute. The onclick event handler captures a click event from the users' mouse button on the element to which the onclick attribute is applied. This action usually results in a call to a script method such as a JavaScript function [...]


1 Answers

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.

like image 86
Fernando Vieira Avatar answered Sep 22 '22 05:09

Fernando Vieira