select box jquery is not defined - ruby-on-rails

I can not get rid of this error, and its to the point where i just started adding sources to the header hoping something would work. What could possibly be causing these errors? this is a form helper in rails.
Uncaught ReferenceError: jQuery is not defined
at select2.self-3d0dca634dc5f4aee8c2dddef05674d9a674214500fd7e89959dc9e7251bb717.js:18
at select2.self-3d0dca634dc5f4aee8c2dddef05674d9a674214500fd7e89959dc9e7251bb717.js:20
reports.self-125a9126dcda5f55eea80b80380e4bf42b79fb01ceba6fbb8c52674b3952fca7.js:2 Uncaught TypeError: $(...).select2 is not a function
at reports.self-125a9126dcda5f55eea80b80380e4bf42b79fb01ceba6fbb8c52674b3952fca7.js:2
at reports.self-125a9126dcda5f55eea80b80380e4bf42b79fb01ceba6fbb8c52674b3952fca7.js:4
reports:59 Uncaught SyntaxError: missing ) after argument list
application.self-a24973bbb6a25a64ef1e551cdacacf83cdc7ddd8e2ea49e5c4df1e07a115c569.js?body=1:24 Uncaught TypeError: $(...).select2 is not a function
at HTMLDocument. (application.self-a24973bbb6a25a64ef1e551cdacacf83cdc7ddd8e2ea49e5c4df1e07a115c569.js?body=1:24)
at fire (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3363)
at Function.ready (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3583)
at HTMLDocument.completed (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3618)
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</header>
<h1>Partner Scorecard Generator</h1>
<%= form_for(:report) do |f| -%>
<p>
<%=f.label "Run date" %><br>
<%=f.date_field :run_date %><br>
</p>
<p>
<script type = "text/javascript">
$(document).ready(function() {
console.log("setting up select 2");
$("#selecttwo").select2({
placeholder: "Select your Partners",
ajax: {
url: 'http://services.dwmholdings.com/order.svcs/api/partners',
dataType: 'json',
type: 'post',
processResults: function p(data){
console.log(processresults())
var mapped = $.map(data, funtion (obj){
obj.text = obj.text || obj.name;
obj.id = obj.id || obj.salesId;
console.log(mapped);
return obj;
})
return {
results: mapped
}
}
}
});
});
console.log("hello")
</script>
<%= select_tag :sales_ids %>
</p>
<p>
<%= f.label "Yes send Email" %>
<%= f.radio_button :send_email, "True" %><br>
<%= f.label "Do not Email" %>
<%= f.radio_button :send_email, "False" %>
</p>
<p>
<%= f.label "recipients" %>
<%= f.email_field(:recipients) %>
</p>
<p>
<%= f.label "bcc" %>
<%= f.email_field(:bcc)%>
</p>
<p>
<%= f.radio_button :Send_Email, "True" %>
<%= f.label :Debug, "Debug on" %><br>
<%= f.radio_button :Send_Email, "False" %>
<%= f.label :Debug, "Debug off" %>
</p>
<p>
<%=f.submit %>
</p>
<!-- :class => "selecttwo",
:multiple=>true,
:size =>20,
:id => "selecttwo" -->
<% end %>

You are loading jquery.min.js as well as jquery.js. Try removing one of those two. This error occurs if sister or same javascripts are getting loaded on same page.

$("#foo").select2()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<div id="foo"></div>
Trying using https instead of http in your script src. Seems to work in this simplified example.

Related

Google recaptcha disappears after second click in the signup button on navbar

In my website recaptcha disappears after second click in sign up button or home button in top navbar. User can signup without verification. How to solve it.
<h2>Create Blog</h2>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), class: "form-horizontal" ) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :username, required: true, autofocus: true, hint: 'no special characters, no numbers only letters [a-z]' %>
<%= f.input :password, required: true, hint: ("#{#minimum_password_length} characters minimum" if #minimum_password_length) %>
<%= f.input :password_confirmation, required: true %>
<div id="g-recaptcha" class="g-recaptcha" data-sitekey="6LcOGEgUAAAAAOxXmBxxxxxxxx"></div>
</div>
<div class="form-actions">
<%= f.button :submit, "Create Blog", data: { disable_with: "This may take upto 2 minutes... "} %>
</div>
<% end %>
<%= render "devise/shared/links" %>
<script>
var captcha_interval;
var myCallback=function(){
document.getElementsByName('commit')[0].disabled=false;
};
var onloadCallback = function() {
document.getElementsByName('commit')[0].disabled=true;
grecaptcha.render(
document.getElementById('g-recaptcha'),
{
callback: myCallback,
sitekey: "6LcOGEgUAAAAAOxXmBVgxxxxxx"
});
};
</script>
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var onloadCallback = function() {
grecaptcha.render('example3', {
'sitekey' : '6LcOGEgUAAAAAOxXmBVgxxxxxx',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
As per reference google-captcha, you are missing the
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
after the form.
Please try adding after form and let me know

concatenate fields in another fields with auto refresh

I m new in rails and html....
I want to concatenate first name and last name in a field fullname in a view. I want that when you modify last name or first name, full name is automatically refreshed with 'first name' +" " + 'lastname'
I tried this but Ive an error. because, seems that full name field stays empty and I tried to make an alert in function to see if concatenation is working. But seems not to do it....
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<script type="text/javascript">
function test ()
{
$('fullname').value <= $('firstname').value + " " + $('lastname').value;
}
</script>
<div class="form-group">
<%= f.label :prenom %><br />
<%= f.text_field :firstname, autofocus: true, placeholder: "Prenom", class: "form-control",:onchange => "test()" %>
</div>
<div class="form-group">
<%= f.label :lastname %><br />
<%= f.text_field :nom, autofocus: true, placeholder: "Nom", class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :fullname %><br />
<%= f.text_field :fullname, autofocus: true, placeholder: "Full Name", class: "form-control", :readonly => true %> <!-- ajout de readonly -->
</div>
Thanks for helping
You should check (or post to your question) your resulting html so I'll may help you more.
This is incorrect:
$('fullname').value <= $('firstname').value + " " + $('lastname').value;
Here the working example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<script type="text/javascript">
$( document ).ready(function() {
$('input.firstname, input.lastname').on('input', function(e) {
var changedFullName = $('input.firstname').val() + " " + $('input.lastname').val()
$('input.fullname').val(changedFullName);
});
});
</script>
<label for="firstname">FirstName</label><br>
<input type="text" name="firstname" class="firstname" /><br>
<label for="lastname">LastName</label><br>
<input type="text" name="lastname" class="lastname" /><br>
<hr>
<span>FullName</span><br>
<input type="text" name="fullname" class="fullname" readonly />
</form>

Not sure file is being read: Uncaught ReferenceError: Stripe is not defined

So I have been having an interesting time trying to get Stripe up and running in my app, currently the problem is that a payment token is not being generated for transactions. When I try to process a test payment I get this error: Must provide source or customer.
Inside of console I get this error: Uncaught ReferenceError: Stripe is not defined
I think the problem is that the <script type="text/javascript" src="https://js.stripe.com/v2/"></script> file is not being read, as it is what should be giving me my token. I have been at this for quite some time, and have read everything I could get my hands on online, but haven't found a solution that works for me yet. It is probably something small, and any help is really really appreciated.
Here is my controller:
require "stripe"
class ChargesController < ApplicationController
def new
#project = Project.find(params[:project_id])
end
def create
binding.pry
#project = Project.find(params[:project_id])
Stripe.api_key = "sk_test_JlKC4V7nmCQ0sE4iNAVyoAxA"
#Get the credit card details submitted by the form
token = params[:stripeToken]
# Amount in cents, this is being read and recorded in stripe dashboard
amount = (params[:amount].to_f * 100).to_i
charge = Stripe::Charge.create(
:amount => amount,
:source => token,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
#save what we need for our server as a new payment
binding.pry
#payment = Payment.create({
user_id: current_user.id,
project_id: #project.id,
amount: #amount,
comments: params[:comments]
})
#make a function in payments model that will convert the cents back into dollars
#project.addMoney(#amount) #add it to project
#payment.save
end
private
def charges_params
params.require(:payment).permit(:comments, :user_id, :project_id, :amount)
end
end
I am not creating a customer, as I was explicitly told by Stripe support via email, that I need not if I am only processing one-time payments, which I am. Here is the payment form, which includes the Javascript in the head (as per Stripe's example):
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
// The required Stripe lib
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('<%= ENV['SECRET_KEY'] %>');
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
}
$('#payment-form').submit(function(event) {
var $form = $(this);
alert('you clicked submit');
console.log('this function was hit');
// Disable the submit button to prevent repeated clicks
$form.find('submit').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
</script>
</head>
<!-- form -->
<div class="container">
<div class="row Row one">
<div class="col-sm-12 col-md-10">
<h1>Make your contribution</h1>
<%= form_for #project, url: project_charges_path, :html => {:id => "payment-form"}, method: 'post' do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :#project_id, :value => #project.id %>
<div class= "field">
<%= label_tag :card_number, "Credit Card Number" %><br>
<%= text_field_tag :card_number, nil, name: nil, class: 'form-control', :required => true %><br>
</div>
<div class= "field">
<%= label_tag :card_code, "Security Code (cvc)" %><br>
<%= text_field_tag :card_code, nil, name: nil, class: 'form-control', :required => true %><br>
</div>
<div class= "field">
<%= label_tag :card_month, "Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"} %>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}%>
</div>
<div class= "field">
<%= label_tag :amount, "Amount" %><br>
<%= text_field_tag :amount, nil, name: nil, class: 'form-control', :required => true %>
</div>
<div class= "field">
<%= label_tag :comments, "Add a comment?" %><br>
<%= text_area_tag :comments, nil, name: nil, class: 'form-control', :required => true %>
</div>
<div class= "actions">
<%= f.submit 'Submit', :class => 'contribution-submit' %>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
<% end %>
</div>
</div>
<!-- <div class="row"></div> -->
</div>
Another thing I find odd that may be worth mentioning in case it is indicative of what the problem may be - the files in this view folder (where the form lives) are not picking up any of the sites css which is provided in the application.html.erb. That is why I had to manually include it in the head of the form's html.erb, as well as include the js.stripe.com file. The css is now rendering, but this file does not seem to be doing anything.
not sure what did it exactly, but went back and copied Stripes code again and it now works. My form now looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Contribution Form</title>
<!-- The required Stripe lib -->
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('<%= 'pk_test_KfCg1YmVXwBYyEdPEWnfibF8'%>');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#payment-form').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()}, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
</head>
<body>
<!-- form -->
<div class="container">
<div class="row Row one">
<div class="col-sm-12 col-md-10">
<h1>Make your contribution</h1>
<%= form_for #project, url: project_charges_path, :html => {:id => "payment-form"}, method: 'post' do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :#project_id, :value => #project.id %>
<div class= "field">
<%= label_tag :card_number, "Credit Card Number" %><br>
<%= text_field_tag :card_number, nil, name: nil, class: ' card-number form-control', :required => true %><br>
</div>
<div class= "field">
<%= label_tag :card_code, "Security Code (cvc)" %><br>
<%= text_field_tag :card_code, nil, name: nil, class: 'card-cvc form-control', :required => true %><br>
</div>
<div class= "field">
<%= label_tag :card_month, "Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, class: "card-expiry-month"} %>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, class: "card-expiry-year"}%>
</div>
<div class= "field">
<%= label_tag :amount, "Amount" %><br>
<%= text_field_tag :amount %>
</div>
<div class= "field">
<%= label_tag :comments, "Add a comment?" %><br>
<%= text_area_tag :comments %>
</div>
<div class= "actions">
<%= f.submit 'Submit', :class => 'contribution-submit' %>
</div>
<div id="stripe_error">
<noscript>JavaScript is not enabled and is required for this form. First enable it in your web browser settings.</noscript>
</div>
<% end %>
</div>
</div>
<!-- <div class="row"></div> -->
</div>
</body>
</html>

Rails - Drop down list with 'other' that allows creation of new model object

I currently have a rather complicated _request_form for creating new Requests in my website. Currently, when creating a request, employees must choose their name from a dropdown menu like so:
<%= f.collection_select :name, Employee.all(:order => 'name'), :name, :name %>
This selects puts the right Employee in the Request. However, on the off chance the employee isn't in database I'd like an other option in the collection_select that spawns two textboxes (for Employee name and email), and upon form submission makes the new Employee.
I assume this requires some sort of fancy Ajax, but my limited Rails knowledge doesn't extend that far!
Edit:
Here's my full view:
<%= javascript_include_tag :defaults, "nested_form" %>
<div class="request_form">
<% if !#request.errors.empty? %>
<div class="alert alert-error">
<ul>
<% #request.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="well">
<%= nested_form_for #request, html: { multipart: true } do |f| %>
<%= f.label :title %><br />
<%= f.text_field :title %><br /><br />
<%= f.label :name, 'Submitted By' %><br />
<%= f.select :name, Employee.sorted_employees_list.map { |value| [ value, value ] }, :id => "employee_box" %><br />
<div id="new_employee_data">
</div>
<%= f.label :description %><br />
<%= f.text_area :description %><br /><br />
<%= f.label :attachment_uploader, 'Attachments' %><%= f.file_field :attachment_uploader, :multiple => true, name: "data_files[attachment_uploader][]" %><br />
<% unless #request.data_files.empty? %>
<%= f.label :attachment_uploader, 'Current Attachments:' %><br />
<% end %>
<%= f.fields_for :data_files do |attachment| %>
<% if !attachment.object.new_record? %>
<%= attachment.label :attachment_uploader, 'Delete: ' + attachment.object.attachment_uploader_url.split("/").last %>
<%= attachment.check_box :_destroy %>
<% end %>
<% end %>
</div>
</div>
<script>
$(document).ready(function(){
$('#employee_box').append("<option>Other</option>");
});
$('#employee_box').change(function() {
if( $('#employee_box').val() === 'other' ) {
$('#new_employee_data').append("<input type='text' id='employee_name' placeholder='Employee Name'> <br/> <br /></input><input type='email' id='employee_email' placeholder='Employee Email'> </input>");
}else {
$('#employee_name').remove();
$('#employee_email').remove();
}
});
</script>
This includes #Kirti's suggestion. However, I can't seem to make it work!
Popup dialog is good choice, I think!
1) Add to your Gemfile, and run bundle:
gem 'jquery-ui-rails'
2) Activate jquery-ui javascript (application.js):
//= require jquery.ui.dialog
3) Link jquery-ui stylesheets (application.css):
*= require jquery.ui.dialog
4) Prepare data for select (employees_controller.rb)
def new
#prices = Price.all.map{|p| [p.price, p.id] }
#prices << ['Create New', 'new_id']
end
5) Display select component on view (employees/new.html.erb):
<%= select_tag :employee, options_for_select(#employees) %>
<div id="new_employee_dialog">
<label for="name" type="text">Employee name:</label>
<input name="name" type="text"/>
<label for="email" type="text">Employee email:</label>
<input name="email" type="email"/>
</div>
6) This javascript work with dialog window and send ajax request (assets/javascripts/employees.js.coffee):
$ ->
$("#new_employee_dialog").dialog
modal: true
width: 400
height: 300
autoOpen: false
draggable: false
dialogClass: "without-header"
buttons: [
text: "Cancel"
click: ->
$(this).dialog "close"
,
text: "Ok"
click: ->
modalForm = $(this)
$.post "/users/form_create",
employee_name: $(modalForm).find("input[name='name']").val()
employee_email: $(modalForm).find("input[name='email']").val()
, (data, status) ->
if data['status'] == 'ok'
modalForm.dialog "close"
alert "Ok"
else
alert "Oops"
]
$('#employee').change ->
selected_employee_id = jQuery("#employee").val()
console.log('selected id: ' + selected_employee_id )
if selected_employee_id == 'new_id'
$("#new_employee_dialog").dialog("open");
7) Create method to catch ajax request on server-side (employees_controller.rb):
def form_create
employee_name = params[:employee_name]
employee_email = params[:employee_email]
# create new user..
respond_to do |format|
format.json { render :json => {status: 'ok'} }
end
end
8) Add it to routes.rb:
post 'users/form_create' => 'users#form_create'
Add an empty div tag(placeholder) where you want to spawn the two input fields:
<div id="new_employee_data">
</div>
Add the following jQuery at the bottom of the view:
<script>
$(document).ready(function(){
$('#request_name').append("<option value='other'>Other</option>");
});
$('#request_name').change(function() {
if( $('#request_name').val() === 'other' ) {
$('#new_employee_data').append("<input type='text' id='employee_name' placeholder='Employee Name'> <br/> <br /></input><input type='email' id='employee_email' placeholder='Employee Email'> </input>");
}else {
$('#employee_name').remove();
$('#employee_email').remove();
}
});
</script>
where,
replace #request_name with the id generated for your collection_select.
You will also need to add code for creating the new employee in the action which is executed at form submission.
NOTE: I am no expert in AJAX but you could adapt the above jQuery and take it from there.

show rest of a form if a checkbox is ckecked in ruby on rails

I need to ask to my user if will pay a service with credit card...if it checked the option pay_with_card? it must show the rest of the form, that ask for other data like card number, mail, etc. if the user don't checked it, it must show a message, the question is...how can I do this? thanks in advance
<%= form_for(#product) do |f| %>
<%= f.label :pay_with_card? %>
<%= f.check_box :pay_with_card,{}, "Yes", "No"%>
<div>
<%= f.label :card_number %> <%= f.text_field :card_number %>
</div>
<div>
<%= f.label :mail %> <%= f.text_field :mail %>
</div>
<% end %>
Make the card number/mail details div style="display:none;", then add some javascript to the checkbox to change it to display:block;
Something like this:
<%= form_for(#product) do |f| %>
<%= f.label :pay_with_card? %>
<%= f.check_box :pay_with_card,{}, "Yes", "No"%>
<div id="card_details" style="display:none;">
<%= f.label :card_number %> <%= f.text_field :card_number %>
<%= f.label :mail %> <%= f.text_field :mail %>
</div>
<% end %>
<script type="text/javascript">
var checkbox = document.getElementById('product_pay_with_card');
var details_div = document.getElementById('card_details');
checkbox.onchange = function() {
if(this.checked) {
details_div.style['display'] = 'block';
} else {
details_div.style['display'] = 'none';
}
};
</script>
How about using jQuery?
First, wrap your credit card fields in a div with class credit_card_fields and than add this JS code to your page:
$("input[type='checkbox']#pay_with_card").on('change', function(){
$('.credit_card_fields').toggle();
});
You can use JS for it or move pay_with_card out of form like:
<%= link_to 'pay with card', your_current_path(:pay_with_card => 1) %>
<%= form_for(...) do |f| %>
<% if params[:pay_with_card] %>
<%= # fields for card %>
<% end %>
<% end %>
You can do it through jQuery, for example:
$ ->
$('select#pay_with_card').change ->
if $(this).val() == 'yes'
$('.card_block').slideDown('fast')
else
$('.card_block').slideUp('fast')
assumed that part of the form with payment card is included in the div with .card_block class
Ok my solution is this: all the code in the view, if a user check pay_with_card...(mi code is in spanish) it shows the complete form...if is not checked donĀ“t show nothing, just the same checkbox asking for payment... thanks guys.
function mostrar (){
var checkbox = document.getElementById('chk_tarjeta');
if (checkbox.checked)
document.getElementById("card_details").style.display = "block";
else
document.getElementById("card_details").style.display = "none";
</script>
<h1>Forma de Pago</h1>
<%= form_for(#product) do |f| %>
<div id="product_pay_with_card">
<div >
<%= f.label :paga_con_tarjeta? %></br>
<%= f.check_box :paga_con_tarjeta, :id => "chk_tarjeta", :onclick => "mostrar();" %>
<div>
</div>
</div>
<div id="card_details" >
<div>
<%= f.label :numero_de_tarjeta %></br>
<%= f.text_field :numerotarjeta %>
</div>
<div>
<%= f.label :codigo_de_seguridad %></br>
<%= f.text_field :codigoseguridad %>
</div>
This worked for me with a form_with model and bootstrap
Change my_hidden_form with an id that makes sense for your form.
Original code is haml
= form_with scope: :model, url: models_path, local: true do |form|
.row
.col-6
.form-group
%h5.mb0 THE CASE TO TICK
= form.check_box :form_value, {:data => {:aria => {controls: :my_hidden_form, expanded: false}, :toggle => "collapse", :type => "checkbox", :target => "#my_hidden_form" }}
.row
.col-6
.form-group.collapse#my_hidden_form
%h5.mb0 THE FORM TO SHOW WHEN CASE IS TICKED
= form.text_field :name, placeholder: "A name"
.row
.col-md-12.text-right
= form.submit 'Submit', class: "btn btn-primary"
Converted to erb/html with https://haml2erb.org/
<%= form_with scope: :model, url: models_path, local: true do |form| %>
<div class="row">
<div class="col-6">
<div class="form-group">
<h5 class="mb0">THE CASE TO TICK
<%= form.check_box :form_value, {:data => {:aria => {controls: :my_hidden_form, expanded: false}, :toggle => "collapse", :type => "checkbox", :target => "#my_hidden_form" }} %>
</h5>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group collapse" id="my_hidden_form">
<h5 class="mb0">THE FORM TO SHOW WHEN CASE IS TICKED
<%= form.text_field :name, placeholder: "A name" %>
</h5>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<%= form.submit 'Submit', class: "btn btn-primary" %>
</div>
</div>
<% end %>
Since the approach suggested by #Unixmonkey didn't work for me, here's a slight variation I put together using an event listener.
<script type="text/javascript">
const checkbox = document.getElementById('product_pay_with_card');
const details_div = document.getElementById('card_details');
checkbox.addEventListener("change", (event) => {
if (event.currentTarget.checked) {
details_div.style['display'] = 'block';
}
else {
details_div.style['display'] = 'none';
}
});
</script>

Resources