0

I have a rails form with a submit button, but I'm wondering if it's possible to make this submit button 1) Post to controller create action and also 2) Execute Javascript

Here are the two buttons I essentially want to combine:

1. <%= f.submit "Go!", class: "btn btn-primary btn-large btn-block" %>

2. <a href="javascript:ExtInstall()" class="btn btn-default btn-large btn-block" role="button">Download our Google Chrome extension</a>

2 Answers 2

3

Yes, you can do this by adding an onClick handler in JS to the submit button.

You can see submit_tag with javascript function for the different ways you can do this.

Sign up to request clarification or add additional context in comments.

3 Comments

hmm can't get it to work, i've tried: <%= f.submit "Go!", onclick: "javascript:ExtInstall(), class: "btn btn-primary btn-large btn-block" %> and then all that happens when I click is I get a popup saying javascript:ExtInstall() rather than the function executing. Have also tried just onclick: "ExtInstall()" in which case the form runs but the installation doesn't trigger. Also tried using confirm instead of onclick
onclick: "ExtInstall()" should work. Try debugging with alert() or console.log to see if ExtInstall() is being called. BTW, the better option is to use jQuery based onclick event handler as discussed here: stackoverflow.com/questions/1070760/…
It doesn't and console.log shows that it's not being called, but I'm not sure why...
0

If your button is part of a form, you can keep its functionality the same as it is now. If it's stand-alone, you'll be best using button_to like so:

<%= button_to "Download", post_path, id: "button" %> # -> uses POST http verb, so will send to create action

What you're asking is best answered with unobtrusive javascript. This will bind your button's click event to a function of your choice, allowing you to not only submit the required data, but handle the other functionality you need too:

#app/assets/javascripts/application.js
$("#button").on("click", function(){
    ExtInstall(); //do you have any references for this function?
});

1 Comment

Hmmm... doesn't work for me. I used a console.log and ExtInstall is just not being called, same as when I tried DevDude's suggestion above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.