Trigger jQuery with form_for in Ruby on Rails - javascript

I'm new in Ruby on Rails and I'm trying to make to form_for trigger a jQuery function.
My code for the form is the next:
<%= form_for #company, :url => create_paying_registration_path(:industry => apt(#plan.industry, :industries), :plan => #plan.name),
:html => {:id => "card-form"} do |f| %>
<%= render 'form_carrier', :company => #company, :plan => #plan, :f => f %>
<% end %>
And jQuery:
jQuery ($) ->
$("#card-form").submit ->
$form = $(this)
$form.find("button").prop "disabled", true
Conekta.token.create tokenParams, conektaSuccessResponseHandler, conektaErrorResponseHandler
false
return
The form doesn't trigger the jQuery function but if I use a form_tag, it triggers the jQuery function:
<%= form_tag('/checkouts/charge', id: 'card-form') do %>
My question is, what am I doing wrong with form_for?
I need to trigger the jQuery and then redirect to the path from form.
Thanks in advance.

Add onSubmit to form_for
form_for #paintings, :url => "/paintings/handlelike", :method => "post", :remote => true, :html => {:id => "submit_form_id",:onsubmit => "yourFunction();", :name => 'form'} do |f|
And in your js:
yourFunction() {
$form = ...
...
}

Related

f.checkbox - how to add onclick that submits instantly?

So I have a check_box in rails 5, and I want it to submit instantly whenever it is clicked/unclicked. It should be possible with :onclick, but I'm new to js/jquery/ajax, and haven't had any luck searching.
I have this:
<%= form_for #client, :url => url_for(:controller => 'client_admin', :action => 'clientadminpageupdate') do |f| %>
<%= f.check_box :visible, :id => "checkbox" %>
<%= f.submit 'Save' %>
What I want to this is submit the form instantly by adding an
:onclick => something-that-submits-the-form-instantly
How do I go about it?
If you just want to use it as a form submission you can use the following:
:onclick => "this.form.submit()"

Why is the link_to submitting form twice?

I am trying to use JavaScript with jquery in rails to update a div without reloading the page. Its working but the comment is being created twice. I know something is wrong in the form partial but couldn't figure it out. Any help?
The following are the files -
_new_comment.html.erb
<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %>
<div>
<%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %>
<%= f.hidden_field :post_id, :value => post.id %>
<span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span>
</div>
<% end %>
comments_controller.rb
def create
#comment = Comment.new(comment_params)
#comment.user_id = current_user.id
if #comment.save
flash[:notice] = 'Comment added sucessfully'
respond_to do |format|
format.html { redirect_to home_posts_url }
format.js
end
end
end
create.js.erb
$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>');
$("#comment-new-83")[0].reset();
home.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
$(document).ready(function() {
$("#comment-new-83").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), null, "script");
return false;
})
})
form_for will automatically post to the controller. You need not submit the form explicitly using jquery.
Reference

How do I make clicking a link_to open up a partial only once?

I have these files:
_comment.haml
%div.comment{ :id => "comment-#{comment.id}" }
%hr
- if current_user && current_user.id == comment.user_id || current_user && current_user.id == reel_user
= link_to "×", comment_path(comment), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this comment?", :disable_with => "×", :class => 'close', :id => "delete_comment"
%h4
= comment.user.first_name
%small= comment.updated_at
%p= comment.body
%p= link_to "Reply", reply_comment_path(comment), :method => :get, :remote => true
comments_controller.rb
def reply
#comment = Comment.find(params[:id])
#obj = Event.find(#comment.commentable_id)
#div_id = "comment-#{#comment.id}"
respond_to do |format|
format.js
end
end
reply.js.erb
$("<%= j render(:partial => 'reply', :locals => { :comment => Comment.build_from(#obj, current_user.id, ""), :parent_comment => #comment }) %>").insertAfter($('#<%= #div_id %>')).show('fast');
_reply.haml
.reply-form
= form_for comment, :remote => true do |f|
= f.text_area :body, :input_html => { :rows => "2" }, :label => false
= f.text_field :commentable_id, :as => :hidden, :value => comment.commentable_id
= f.text_field :commentable_type, :as => :hidden, :value => comment.commentable_type
= f.text_field :p_comment, :as => :hidden, :value => parent_comment.id
= f.submit "Reply!", :class => "btn btn-primary", :disable_with => "Submitting…"
That's basically the flow of what happens if you click "Reply" in _comment.haml. If you click "Reply", then the partial from _reply.haml opens up underneath the _comment.haml partial. However, if you click "Reply" more than once it will continue opening more _reply partials. How can I make it so that it only opens the form once and if you click it again then nothing happens?
Also, how can I make it so that if there's comment 1 and 2 and the reply partial is open for comment 1, if you click "Reply" on comment 2, it will open up the reply partial for comment 2 and close the partial for comment 1. Thanks!
There's lots of ways to do this.
In reply.js.erb before rendering the form, first remove any existing forms on the page, this action should prevent multiple reply forms coming up, and close reply forms from another reply click.
this line goes at the top of reply.js.erb
$('.reply-form').remove();
One side-effect of this answer is that if a person starts filling in the reply form and then they click on "Reply" again before they submit the form, then what they've typed will be lost

Rails 3.2 - Ajax call when text field changes

I have a Rails 3.2.13 app with some Ajax on forms and links, using the remote parameter.
The problem is that i can't find in the docs how to do the same with text fields - the
remote parameter didn't work, so i think it's not supported on input objects.
I'd like to do bind 'ajax:xxx' events (like 'ajax:success') on my text_field objects.
I this even possible with UJS? If not, what my options are?
Here's some code:
<%= form_for #post, :html => {:class => 'form-horizontal'} do |f| %>
<div class = 'control-group'>
<%= f.label :title, :html => {:class => 'control-label'} %>
<%= f.text_field :title, :placeholder => 'Title', :class => 'input-xxlarge' %>
</div>
<div class = 'control-group'>
<%= f.label :body, :html => {:class => 'control-label'} %>
<%= f.text_area :body, :placeholder => 'Your post here', :class => 'input-xxlarge',
:rows => 15 %>
</div>
<div class = 'control-group'>
<%= f.label :tags, :html => {:class => 'control-label'} %>
<%= f.text_field :tags, :placeholder => 'Tags separeted by ,', :class => 'input-xxlarge',
:value => '' %>
</div>
<%= f.submit 'Create', :class => 'btn btn-primary'%>
Thanks!
I would bind a change or blur event to the input, and then make the Ajax call manually on your javascript/coffecript file.
posts.js
$('#post_title').change(function() {
// Do your stuff, instantiate variables, etc...
$.ajax({
type: post_or_get,
url: your_url,
data: your_data,
success: function(data) {
// Handle stuff after hitting the server here
},
error: function(data) {
}
});
});

validation before ajax form submission

How do i introduce validation before remote_form_for submits?
I have javascript function called validateForm(). I am able to call it before the AJAX request process. I tried to use return false and event.preventDefault. But there seems to be no effect. Here is what my code looks like
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv", :url => {:action => "login", :controller => "site"}, :onsubmit => "validateForm(event)" do |f| %>
User name : <%= f.text_field "uxUserName", :class => "TextBox", :style => "width:100px;" %> *
Password : <%= f.password_field "uxPassword", :class => "TextBox", :style => "width:100px;" %> *
<%= f.submit "Go!", :class => "Button-Simple", :id => "uxSubmitButton" %>
<% end %>
the javascript function is simple as follows
function validateForm(event){
return false;
//event.preventDefault();
}
Try this
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv", :url => {:action => "login", :controller => "site"}, :html => {:id => "uxLoginForm"}, :onsubmit => "return validateForm(event)" do |f| %>
i.e. change
:onsubmit => "validateForm(event)
to
:onsubmit => "return validateForm(event)
EDITED it should be
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv",
:url => {:action => "login", :controller => "site"},
:html => {:id => "uxLoginForm", :onsubmit => "return validateForm(event)"}
do |f|
%>
EDITED AGAIN
WHY don't you use :condition for it? something like following
<% remote_form_for :customer, :update =>"uxScreenLoaderDiv",
:url => {:action => "login", :controller => "site"},
:html => {:id => "uxLoginForm"},
:condition=>"validateForm(event)!=false"
do |f|
%>
I think what you're looking for is something like onSubmit="return validateForm(this)" or thereabouts. Then if the validation returns false (because it failed validation) the form should not submit.
You might want to check LIvevalidation plugin (http://github.com/augustl/live-validations) which you can you to do Ajax with active record validations
And its always good to have non-ajax validations also (even though you use ajax validations) as ajax will not work in javascript disable browser
cheers,
sameera

Categories

Resources