Send checkbox value to rails model field - javascript

I would like to send the value of my checkbox (true/false) to my rails model field (:taxable) on the state change of that button.
So far I have this, but I am not sure where to go from here
<script>
$(document).ready(function() {
$('.taxable').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
/* */
});
});
</script>
<%= f.input :taxable, :as => :boolean, hint: "Is order taxable?",:id => 'taxable', :class => "taxable", :remote => true %>

Try this :
<script>
$(document).ready(function() {
$('.taxable').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
$.ajax({
type: "POST",
url: "/url",
data: { params: { taxable: isChecked } },
success:(data) {
alert(data)
return true;
},
error:(data) {
return false
}
})
/* */
});
});
</script>
<%= f.input :taxable, :as => :boolean, hint: "Is order taxable?",:id => 'taxable', :class => "taxable", :remote => true %>

Related

Rails cocoon gem: populate multiple fields

I'm using the cocoon gem on my rails app and I have two nested fields inside a form (categories, subcategories). Initially I'm showing the first one only and the second one is hidden. Each time the first select fields has subcategories the second field gets populated and appears.
The nested fields:
<div class="nested-fields">
<%= form.input :category, collection: #categories, as: :grouped_select, group_method: :children, :label => false, :include_blank => true, input_html: { id: "first_dropdown" } %>
<div class="show_hide">
<%= form.input :subcategories, label: false, :collection => [], :label_method => :name, :value_method => :id, required: true, input_html: { multiple: true, id: "second_dropdown" } %>
</div>
<div class="links">
<%= link_to_remove_association "Remove", form %>
</div>
</div>
This is the code to initially hide the second field
$('#first_dropdown').keyup(function() {
if ($(this).val().length == 0) {
$('.show_hide').hide();
}
}).keyup();
This is the code to show the second select input when the first select input has subcategories:
def select_item
category = Category.find params[:category_id]
render json: category.children
end
$('#first_dropdown').on('change', function() {
$.ajax({
url: 'categories/select_item?category_id=' + $(this).val(),
dataType: 'json',
success: function(data) {
let childElement = $('#second_dropdown');
if( data.length === 0 ) {
$('.show_hide').hide();
} else {
$('.show_hide').show();
}
childElement.html('');
data.forEach(function(v) {
let id = v.id;
let name = v.name;
childElement.append('<option value="' + id + '">' + name + '</option>');
});
}
});
});
Everything works well for the initial opened field. But when I add more fields and select a value inside any of the first select fields it populates all of the second fields according to that value. I think it's because I'm using specific id's for this and when I add more fields, all of them end up having the same id's. How can I set this up so I properly populate the second select field each time I add more nested fields to the form?
I'd give your selects classes instead of ids:
<div class="nested-fields">
<%= form.input :category, collection: #categories, as: :grouped_select, group_method: :children,
label: false, include_blank: true, input_html: { class: "first_dropdown" } %>
<% if f.object.category && f.object.category.sub_categories.length > 0 %>
<div class="show_hide">
<%= form.input :subcategories, label: false, collection: form.object.category.subcategories, label_method: :name,
value_method: :id, required: true, input_html: { multiple: true, class: "second_dropdown" } %>
</div>
<% else %>
<div class="show_hide" style="display: none;">
<%= form.input :subcategories, label: false, collection: [], label_method: :name,
value_method: :id, required: true, input_html: { multiple: true, class: "second_dropdown" } %>
</div>
<% end %>
<div class="links">
<%= link_to_remove_association "Remove", form %>
</div>
</div>
then find the second select relative to the first one adding this to a page specific js file:
$(document).on('turbolinks:load cocoon:after-insert', function(){
$('.first_dropdown').off('change').on('change', function(){
let $this = $(this);
let $second = $this.closest('.nested-fields').find('.second_dropdown');
$second.children().remove();
$second.closest('.show_hide').hide();
if ($this.val() !== '') {
$.ajax({
url: 'categories/select_item?category_id=' + $(this).val(),
dataType: 'json',
success: function(data){
if (data.length > 0) {
$second.append('<option value=""></option>');
data.forEach(function(v) {
let id = v.id;
let name = v.name;
$second.append('<option value="' + id + '">' + name + '</option>');
});
$second.closest('.show_hide').show();
}
}
})
}
});
});

Disable and enable with checkbox and simple form gem

I'm trying to disable and enable action with checkbox on the post form.
And I don't know much about javascript or JQuery.
And I'm trying to do this action a lot and I don't how to do it, I'm programming alone.
So if anyone could help me with this, I will appreciate!
I'm using a Rails 4.2.8 and jquery-rails-4.3.1 versions.
my form: app/views/posts/_form.html.slim
= simple_form_for(#post, :html => { :multipart => true }) do |f| = f.input :publish,
label: "Publish?",
as: :boolean,
label_html: { class: "publish-check" },
input_html: { checked: false },
remote: true = f.input :published_at, disabled: true, hint: 'You cannot publish your post.',label: "Publish Post at:"
I'm trying to put this on the fileapp/assets/javascript/_form.coffee it's alright or I need to put on another file?
$(document).on "turbolinks:load", ->
$checkbox = $('[id^="post_publish"]')
$select = $('.post_published_at')
$checkbox.change (e) ->
$select.prop 'disabled', !$checkbox.is(':checked')
return
return
This field published_at it's a date time.
So I think now I need to put some array, the id's generated it's likeid="post_published_at_1i" and until id="post_published_at_5i"
If I understood you right, the only way of doing that is with javascript:
= simple_form_for(#post, :html => { :multipart => true }) do |f|
= f.input :publish, label: "Publish?", as: :boolean, input_html: { checked: false }
= f.input :published_at, label: "Publish Post at", style: "visibility: hidden;"
That will create something like the HTML part below, so, you just need to add the javascript to your page and maybe tweak it a little bit.
window.addEventListener('load', function() {
document.getElementById('post_publish').addEventListener('change', function() {
var input = document.getElementById('post_published_at')
if (this.checked) {
input.style.visibility = 'visible';
input.disabled = false;
} else {
input.style.visibility = 'hidden';
input.disabled = true;
}
});
});
<form id="new_post" action="/post" method="post">
<input id="post_publish" type="checkbox">
<label>Publish?</label>
<input id="post_published_at" style="visibility: hidden;">
</form>

Calling javascript function from button_tag?

I have next file with jquery function:
assets/ javascripts/poll_items.js
$(document).ready(function(){
$('.up_id').on('click', function() {
$(this).closest('.poll_row').insertAfter($(this).closest('.poll_row').next());
});
$('.down_id').on('click', function() {
$(this).closest('.poll_row').insertBefore($(this).closest('.poll_row').prev());
});
});
when i click `= button_tag 'up', type: 'button', value: 'up', input_html: {class: 'up_id'}' nothing happens. How me correct call code from file javascript?
full code:
polls/new.html.haml
%h1= title "Новый опрос"
= simple_form_for #poll do |f|
= f.error_messages header_message: nil
= f.input :question, disabled: !#poll.editable?(current_user), input_html: { class: 'input-block-level' }
= f.input :results_hidden, as: :boolean, inline_label: 'Скрыть результаты до окончания опроса', label: false
= f.input :from_date, as: :datetime, input_html: { class: 'poll_date' }
= f.input :to_date, as: :datetime, input_html: { class: 'poll_date' }
%h3#poll-items Варианты ответа (не больше пяти)
.item_index
= f.simple_fields_for :poll_items do |poll|
= render 'poll_item_fields', f: poll
= link_to_add_association 'Добавить еще вариант', f, :poll_items
.form-actions
= f.button :submit, 'Опубликовать опрос', class: 'btn-bg'
%p
Вернуться к посту:
= link_to #owner
poll_fields.html.haml
%h3#poll-items Варианты ответа (не больше пяти)
.item_index
= f.fields_for :poll_items do |poll|
= render "poll_item_fields", f: poll
.links
= link_to_add_association 'Добавить еще вариант', f, :poll_items, render_options: {class: 'links'}
poll_item_fields.html.haml
.poll_row
.poll_item
= f.input :answer, input_html: { class: 'ctrlenter expanding' }, label: false, placeholder: 'Введите вариант ответа'
= button_tag 'up', type: 'button', class: 'up_id', value: 'up'
= button_tag 'down', type: 'button', class: 'down_id', value: 'down'
= link_to_remove_association "удалить", f, { wrapper_class: 'poll_item' }
I am suspecting that the DOM is getting build dynamically so try changing your JS code as follows:
$(document).ready(function(){
$(document).on('click', '.up_id', function() {
$(this).closest('.poll_row').insertAfter($(this).closest('.poll_row').next());
});
$(document).on('click','.down_id', function() {
$(this).closest('.poll_row').insertBefore($(this).closest('.poll_row').prev());
});
});
Here we are using event delegation technique to propagate the click event to required DOM element which may be present in DOM.
SOLUTION:
I added in application.js.coffee #=require poll_items.js and everything works

Stripe Token not passed with Javascript

I am using Stripe to:
Create Customer
Create Purchase
To do this, I am using this javascript code in my purchases.js (for my purchases controller):
$('document').ready(function() {
jQuery.externalScript = function(url, options) {
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
return jQuery.ajax(options);
};
$.externalScript('https://js.stripe.com/v1/').done(function(script, textStatus) {
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
var purchase = {
setupForm: function() {
return $('.card_form').submit(function() {
$('input[type=submit]').prop('disabled', true);
if ($('#card_number').length) {
purchase.processCard();
return false;
} else {
return true;
}
});
},
processCard: function() {
var card;
card = {
name: $('#name_on_card').val(),
number: $('#card_number').val(),
cvc: $('#card_code').val(),
expMonth: $('#card_month').val(),
expYear: $('#card_year').val()
};
return Stripe.createToken(card, purchase.handleStripeResponse);
},
handleStripeResponse: function(status, response) {
if (status === 200) {
$('#purchase_stripe_token').val(response.id)
$('.card_form')[0].submit()
} else {
$('#stripe_error').text(response.error.message).show();
return $('input[type=submit]').prop('disabled', false);
}
}
};
return purchase.setupForm();
});
});
This works fine.
My issue is, I am trying to create a recipient. To do this, I basically use the same code, swapping out the respective fields for the recipient creation. BUT before I do this, I attempt to submit the form (essentially creating a purchase from a different controller), but in the second controller, it does not pass the stripe_token.
What would be the cause for this -- the code is basically the same? I'm not versed in JS.
UPDATE
THIS IS THE JAVASCRIPT THAT DOES NOT WORK.
$('document').ready(function() {
jQuery.externalScript = function(url, options) {
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
return jQuery.ajax(options);
};
$.externalScript('https://js.stripe.com/v1/').done(function(script, textStatus) {
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
var bank = {
setupForm: function() {
return $('.recipient_form').submit(function() {
$('input[type=submit]').prop('disabled', true);
if ($('#account_number').length) {
bank.processBankAccount();
return false;
} else {
return true;
}
});
},
processBankAccount: function() {
var details;
details = {
country: $('#country').val(),
routingNumber: $('#routing_number').val(),
accountNumber: $('#account_number').val()
};
return Stripe.createToken(details, bank.handleStripeResponse);
},
handleStripeResponse: function(status, response) {
if (status === 200) {
$('#bank_stripe_token').val(response.id)
$('.recipient_form')[0].submit()
} else {
$('#stripe_error').text(response.error.message).show();
return $('input[type=submit]').prop('disabled', false);
}
}
};
return bank.setupForm();
});
});
THIS IS THE FORM.
<%= form_for([#user, #bank], role: "form", html:{class: "recipient_form"}) do |f| %>
<%= label_tag :country, "Country"%>
<%= text_field_tag :country, nil, name: nil, required: true %>
<%= label_tag :routing_number, "Routing Number"%>
<%= text_field_tag :routing_number, nil, name: nil, required: true %>
<%= label_tag :account_number, "Accounting Number"%>
<%= text_field_tag :account_number, nil, name: nil, required: true %>
<%= f.hidden_field :stripe_token %>
<%= f.submit value: "ADD" %>
<% end %>
THE CONTROLLER.
class BanksController < ApplicationController
def new
#user = User.find(params[:user_id])
#bank = #user.build_bank
end
def create
#user = User.find(params[:user_id])
#bank = #user.build_bank
stripe_token = params[:bank][:stripe_token]
begin
if !stripe_token.present?
raise "Stripe token not present. Cannot process transaction."
end
recipient = Stripe::Recipient.create(
:name => "Person Name",
:type => "individual",
:bank_account => stripe_token )
end
end
end
FORM DATA:
{"utf8"=>"✓",
"authenticity_token"=>"[FILTERED]",
"bank"=>{"stripe_token"=>""},
"commit"=>"ADD",
"user_id"=>"1680"}

rails tag embedded in html issues

<div class="well original3">
<%= form_tag( { :controller => 'businesses', :action => 'create' }, { :id => 'myform',:class => 'form-inline offset3', :method => 'post'}) do %>
<%= text_field_tag('mnum' ,nil, :class => "input-xlarge", :style => "text- align:center;height:28px;",:placeholder => "Enter Mobile Number") %>
<%= submit_tag "Get", :id => "da",:class => "btn btn-large btn-primary" %>
<%end%>
</div>
JQUERY
$(document).ready(function () {
$("#da").click(function() {
//$(".original3").fadeOut(300, function() {
//$(".original3").css("display", "block");
$(".checked3").css("display", "block");
$(".checked3").show();
//});
});
});
Basically another Div will be hide via css. when click this Get button that div should show, But here is the problem when i click the GET button the the other div will show and fadeout soon. But when i change the GET button type submit to button that will work properly..?
How to avoid this problem...?
Thank you
Use
<%= submit_tag "Get", :id => "da",:onclick => show_checked3();,:class =>"btn btn-large btn-primary" %>
function show_checked3(){
$(".checked3").css("display", "block");
$(".checked3").show();
}
Or Try with
$(document).ready(function () {
$("#da").live('click',function() {
$(".checked3").css("display", "block");
$(".checked3").show();
//});
});
Update
You can try with
$("#myform").submit(function(){
$(".checked3").css("display", "block");
$(".checked3").show();
return true;
});

Categories