How to call a javascript function in a rails form? - javascript

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 ?

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');
});

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>

Related

Submit stops working after first successful submit

I have a simple form in a rails app that is rendered within a partial called roster_panel:
<div id = 'active_admin_content'>
<%= semantic_form_for #roster_item do |form| %>
<h3>Add a counselor</h3>
<div id="counselor_status_message"><%= #status_message %></div>
<%= form.inputs do %>
<%= form.input :first_name, input_html: {id: 'counselor_first_name'} %>
<%= form.input :last_name, input_html: {id: 'counselor_last_name'} %>
<%= form.input :email, input_html: {id: 'counselor_email'} %>
<div class="button_container" >
<input id="submit_counselor_add" type="button" value = "Send forms packet" class = "button" >
</div>
<% end %>
<% end %>
</div>
In my jquery code, I tie the submit click to this:
$( document ).on('turbolinks:load', function() {
$("#submit_counselor_add").click(function(){
$.get("add_counselor_info" , { id: $("#roster_id").text(), first_name: $("#counselor_first_name").val(),
last_name: $("#counselor_last_name").val(), counselor_email: $("#counselor_email").val() },
function(data){ $("#roster_panel").html(data);
}
)
});
});
This routes to this controller method:
def add_counselor_info
#roster = Roster.find(params[:id])
#group = ScheduledGroup.find(#roster.group_id)
#liaison = Liaison.find(#group.liaison_id)
#items = RosterItem.where(roster_id: #roster.id)
#roster_item = RosterItem.new(group_id: #group.id, roster_id: #roster.id,
first_name: params[:first_name], last_name: params[:last_name],
email: params[:counselor_email], youth: false, item_status: 'Unconfirmed' )
if #roster_item.save
#error_count = 0
#status_message = 'This counselor has been added and the forms package has been emailed. You may enter another counselor.'
#items = RosterItem.where(roster_id: #roster.id)
#roster_item = RosterItem.new
else
#error_count = #roster_item.errors.size
#status_message = "#{#error_count} errors prevented saving this information: "
#roster_item.errors.full_messages.each { | message | #status_message << message << ' '}
#items = RosterItem.where(roster_id: #roster.id)
end
render partial: 'roster_panel'
end
After a fresh page load, this process works fine and redisplays the form as expected. However, at that point the submit button no longer triggers the action in jquery. Other jquery functions on the page still work, however. This may have something to do with turbolinks, which I am not very familiar with.
Any help would be appreciated!
After submitting the form, the DOM is replaced by the new one, so on click event binding is being lost.
Try to bind this event through the parent element, which won't be overridden by javascript (e.g. body):
$( document ).on('turbolinks:load', function() {
$("body").on('click', '#submit_counselor_add', function() {
$.get("add_counselor_info", {
id: $("#roster_id").text(),
first_name: $("#counselor_first_name").val(),
last_name: $("#counselor_last_name").val(),
counselor_email: $("#counselor_email").val()
},function(data) {
$("#roster_panel").html(data);
});
});
});

Submit method don't work in rails

I need to replace submit button to "link_to".
#View
<%= form_for :task, remote: true, id: 'create_form' do |f| %>
....
<%= link_to 'OK', '', id: 'submit_link' %>
<% end %>
#CoffeeScript
ready = ->
$("#submit_link").click (event) ->
$("#create_form").submit()
$(document).ready ready
$(document).on "page:load", ready
Click trigger work good, but "submit()" method doesn't work and i don't know why.
Also i try to add "event.preventDefault()", but nothing changed.
I think you need to set the id of your form like this
<%= form_for :task, remote: true, html: { id: 'create_form' } do |f| %>
http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
Or, just use the form id that form_for generates which should be new_task
#CoffeeScript
ready = ->
$("#submit_link").click (event) ->
$("#new_task").submit()
$(document).ready ready
$(document).on "page:load", ready

Rails reCAPTCHA with callback

I am trying to integrate a recaptcha into my website and I wanted to add some client side validation.
I chose to use a gem to include the recaptcha tags, but I wanted to trigger a function once the recaptcha is checked.
Looked through some google sites and found that a data-callback attribute with its value set to function name is all I need.
I used recaptcha_tags helper from the gem to set it up and then a jquery method to add this data-callback attribute as I have not seed an option to do this inside the gem.
$('.g-recaptcha').attr("data-callback", "myFunctionName");
After clicking the recaptcha the function is not called. Why?
I asume you have a form like this
app/views/contacts/contact.html.erb
<%= form_for #contact do |f| %>
<%= f.text_field :nombre, :placeholder => I18n.t("contacto_formulario_nombre"),:required => true %>
<%= f.text_field :apellido :placeholder => I18n.t("contacto_formulario_apellidos"), :required => true %>
<%= f.text_field :email, :placeholder => I18n.t("contacto_formulario_email"), :required => true %>
/** (....other tags ....) **/
<%= recaptcha_tags :display => 'clean' %>
<%= f.button I18n.t("contacto_formulario_continuar"), type: "submit" %>
<% end %>
app/assets/javascripts/contact.js
$(function() {
$('.g-recaptcha').attr("data-callback", "recaptcha");
})
function recaptcha()
{
console.log("captcha pulsado!");
/** the actions you want, i.e. activate submit button **/
}
The magic ocurrs in the attribute "data-callback"
Hope it helps.
Marino

Rails data-remote attribute not always requesting a JS response

I have a form_for with remote: :true, but the problem is that it seems to only be submitted remotely about half of the time. Sometimes I will get a ActionController::UnknownFormat (ActionController::UnknownFormat) error from the server, which is configured to only respond to format.js, and most of the time the form will work perfectly.
Is there some way I can call $.rails to make sure that the data-remote binding is taking effect? I have turbolinks turned off. Here is the code for the form:
= form_for [:admin, #seating_chart], remote: 'true', authenticity_token: true, multipart: true do |f|
%br
.form-group.text-center
= f.label :name
= f.text_field :name, class: 'form-control'
.form-group.text-center
= f.label :venue_id
= f.collection_select :venue_id, Venue.all, :id, :name
.form-group.text-center
= f.label :chart_image
= f.file_field :chart_image, id: :seating_chart_file
.actions.text-center
= f.submit 'Save', class: 'btn btn-primary'
\|
= link_to 'Back', :back, class: 'btn btn-primary'
EDIT: upon further investigation it seems to only happen when I upload an image - if I don't upload the image then the error doesn't occur.
Since you are trying to upload file with ajax request it can't be achieved directly.
The solution for this case is remotipart
Remotipart
And this is a demo of it
Demo

ajax auto form submit with rails4

I'm using rails4.2.0
in my e-commerce site, when a user submit his payment type, I want to redirect outside website. The flow is below.
a user choose payment type
use click submit button
-- ajax (format js) --
redirect to outside website using post method
source of 2 and 3 are like ,
create.html.erb
<%= form_for(:user,:url => { controller: "settlements", action: "settlement"}, remote: true, html: {class: :settlement_form}) do |f| %>
<%= f.radio_button :settlement_type, 0 %>paypal
<%= f.radio_button :settlement_type, 1 %>credit card
<%= f.hidden_field :email, :value => #user.email %>
<%= f.hidden_field :fee_type, :value => #user.fee_type %>
<%= f.submit "Submit", data: { disable_with: "Please wait..." }, class: "btn btn-warning" %>
settlement_controller
def settlement
user = User.new(user_params)
if user.save
# parameters for outside website
#payment_params
else
render "new"
end
end
settlement.js.erb
var form = $('<form></form>',{id:"pay",action:'http://outside_ec_site_url/hoge',method:'POST'}).hide();
var body = $('redirect');
body.append(form);
form.append($('<input/>', {type: 'hidden', name: 'something', value: <%= #payment_params[:something] %>}));
form.append($('<input/>', {type: 'hidden', name: 'something', value: <%= #payment_params[:something] %>}))
form.submit();
I fixed this problem, but I want to know better method.
changed settlement.js.erb like,
$("#redirect").html("<%= escape_javascript(render :partial => 'pay' ) %>");
and created new file _pay.html.erb
<script>
$('<form/>', {id: 'paygent',action: "outside_website_url", method: "POST"})
.append($('<input/>', {type: 'hidden', name: 'something1', value: "<%= #payment_params[:somthing1] %>"}))
.append($('<input/>', {type: 'hidden', name: 'something2', value: "<%= #paygent_params[:something2] %>"}))
.appendTo(document.body)
.submit();
</script>
then, it works.
Do you know any other method? Any idea is appriciated.

Categories