user8116786
user8116786

Reputation:

How to call a javascript function in a rails form?

I have a rails form that looks like this :

= form_for :location, :url=>'/welcome' do |f|
  = f.text_field '', placeholder: 'Enter your zip code', id:'input_id'
  = f.button "Continue", class: 'button-test'

So when the button continue is clicked upon , rails get the controller and execute the method /welcome

so what i am trying to do is to actually execute a simple javascript function like :

function wawa() {
 alert('it works')
};

when the button continue is cliked instead of rails getting to execute the method /welcome.

How can I approach this problem using Javascript only and no library ?

Upvotes: 2

Views: 2396

Answers (2)

Manishh
Manishh

Reputation: 1484

You need to add some JavaScript On submit Listener I suppose you need it before form is submit. If you want only on click then have a look at on click Listener also have a look at event prevent as it will help you to prevent from default behaviour of button.

Try this code

<%=  form_for :location, :url=>'/welcome' do |f| %>
  <%=  f.text_field '', placeholder: 'Enter your zip code', id:'input_id' %>
  <%=  f.button "Continue", class: 'button-test', id: 'demo' %>
 <% end %>

<script type="text/javascript">
    document.getElementById("demo").addEventListener("click", function(event){
        event.preventDefault()
        alert('Hello')
    });
</script>

Upvotes: 0

Khanh Pham
Khanh Pham

Reputation: 2973

You can use submit() function of jquery.

= form_for :location, :url=>'/welcome', html: {id: "id_form_location"} do |f|
 = f.text_field '', placeholder: 'Enter your zip code', id:'input_id'
 = f.button "Continue", class: 'button-test'

In javascript file:

$("#id_form_location").submit(function(event) {
  alert('it works');
});

Upvotes: 2

Related Questions