Add a new form based on another form's data? - javascript

I have a dropdown menu that allows the user to select a time period (ie: January 2018, 1st Trimester, Summer 2018, etc.). At the very bottom there's an option labelled "Other". How can I make it so that if the user selects "Other", and text-input form appears beneath that so that they can elaborate on what "Other" means? Here's my current code:
HTML:
Time Period:
<% if f.object.award.add_period? %>
<div class="time_period_<%= f.object.award.id %>" id="otherBoolID">
<%= f.select :time_period, Award::TimePeriods, {:include_blank => true}, { :class => "date_dropdown"} %>
</div>
<% end %>
<div id="boolID" <%= "hidden" %>>
<%= f.input :time_period, :label => false, placeholder: "Other (please specify)", :input_html => { :class => 'awardform' } %>
</div>
JavaScript/JQuery:
$('#otherBoolID').change(function () {
var x = document.getElementById('otherBoolID').value;
if (x == "Other") {
document.getElementById('boolID').style.display = 'visible';
}
});
Any idea what's going wrong? Currently the "other" form is hidden on page load, but doesn't become visible if you select "Other" in the dropdown menu. If it's worth mentioning, I'm working with a ruby on rails framework.

Could the issue be that the id="otherBoolID" is on the <div> rather than <select> tag?

Related

How to show a form on load

How to show form on load. Now I can see form fields on click of button (add keyskills). I want all function to be work together.On load i want to see the form and onclick 'add key skill' or 'remove key skill' it should add and remove(now on click of add or remove it is working, but not sees the form on load, only on click of 'add key skill' i can see the form)
$(function()
{
function check_to_hide_or_show_add_key_skill_link()
{
if ($('#key_skills .nested-fields:visible').length == 4) {
$('#key_skills .links a').hide();
} else {
$('#key_skills .links a').show();
}
}
$('#key_skills').on('cocoon:after-insert', function()
{
check_to_hide_or_show_add_key_skill_link();
});
$('#key_skills').on('cocoon:after-remove', function()
{
check_to_hide_or_show_add_key_skill_link();
});
check_to_hide_or_show_add_key_skill_link();
});
My form
Key Skills*
<div id="key_skills">
<%= f.simple_fields_for :key_skills do |key_skill| %>
<div class="nested-fields">
<div class="field">
<%= f.input :name , input_html: { class: 'form-control keySkill', required: true }%>
<%= f.input :relevant_experience, input_html: { class: 'form-control', required: true } %>
<%= link_to_remove_association "Remove Skill", f %>
</div>
</div>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Key Skill', f, :key_skills, class: "links" %>
</div>
</div>
This is my current output now. On click of add key skill i will get form,but i want it on load)
Since you do not provide a lot of information, I have no idea what the name of the top-element is, but let us assume it is a Job and a job has many key_skills.
In your JobsController there is a create method, more or less as follows:
def create
#job = Job.new
end
if you want to immediately add a key-skill to fill in you can just write
def create
#job = Job.new
#job.key_skills.build
end
(which will add an empty key-skill to fill in).
Related issue on cocoon-repository: https://github.com/nathanvda/cocoon/issues/420

Using JavaScript/Jquery to show forms with the same id/class in Ruby

I want to have a button for retweets in my web-application. When I press the button I want a form to display in order to add my own text to the tweet.
I implemented this . However I have a problem: all my forms and buttons contain the same id and class, so you can imagine that when I press a button it will display the first form with that id/class instead of the one that it has to show. How can I show the form that I have to show ?
Here are only the parts of the code that contain retweet part(the other parts are not important I think for the problem but I can post them if someone wants me to) :
<button type="buton" id="retweet-button">retweet</button>
<%= form_for(current_user.tweets.build,url: retweet_act_path, method: :post, html: { multipart: true, :class => "retweet_form" }) do |f| %>
<%= f.hidden_field :original_tweet_id, value: tweet.id %>
<%= f.text_area :content, placeholder: "Add a message to the tweet..." %>
<%= f.submit "Retweet"%>
<% end %>
And the JS:
<script type="text/javascript">
$(document).ready(function() {
$('.retweet_form').hide(); //Initially form wil be hidden.
$('#retweet-button').click(function() {
$('.retweet_form').show();//Form shows on button click
});
});
</script>
How can I show the form that I have to show when pressing a certain button ? (I guess I have to have a different ID for every button and form , but how ? )
As I understood from the code, you use one button/form pair per tweet. So that, you are able to use tweet ID to generate form ID. To connect button to appropriate form, use data-* fields.
Generation of forms and buttons on Rails side (NOTE: syntax highlight is broken):
<button type="button" class="retweet-button" data-target-form-id="<%= "#retweet-form-#{tweet.id}" %>">retweet</button>
<%= form_for(current_user.tweets.build,url: retweet_act_path, method: :post, html: { multipart: true, :class => "retweet_form", id: "retweet-form-#{tweet.id}" }) do |f| %>
<%= f.hidden_field :original_tweet_id, value: tweet.id %>
<%= f.text_area :content, placeholder: "Add a message to the tweet..." %>
<%= f.submit "Retweet"%>
<% end %>
And JS:
$('.retweet_form').hide();
$('.retweet-button').click(function() {
var formId = $(this).data('target-form-id');
$(formId).show();
});

How to Change Date Format According to User Selection?

How can I change the date :order according to the User's "f.select :categories" choice?
For example when a User goes to the Quantified _form he can select between "Monthly Average" or "One-Time Instance";
If he selects "Monthly Average" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :year]" if he selects "One-Time Instance" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :day, :year]
Ideally this would be done dynamically via javascript, but I would be happy to accept an answer that does it via the view.
_results_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
<br/>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select' %>
<%= link_to_remove_association "Remove Result", f %>
</div>
</div>
_form.html.erb
<%= form_for #quantified do |f| %>
<div class="america">
<%= f.select :categories, Quantified::CATEGORIES %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :name, class: 'form-control', placeholder: 'Enter Name' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<%= link_to_add_association 'add result', f, :results %>
</div>
<%= f.submit %>
</div>
<% end %>
quantified.rb
class Quantified < ActiveRecord::Base
belongs_to :user
scope :averaged, -> { where(categories: 'Monthly Average') }
scope :instance, -> { where(categories: 'One-Time Instance') }
has_many :results
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true
CATEGORIES = ['Monthly Average', 'One-Time Instance']
end
Github: https://github.com/RallyWithGalli/ruletoday
Thank you for your time.
The answer here was to use some jquery provided by the gem that was being used to add the date selects, as well as some jquery of our own
First things first, we rig up the checkboxes with a click() event, that hides anything with the class 'day' if instance is checked, and shows it if not.
$('.date-toggle').click(function(){
if( $(this).attr('id') == 'instance') {
$('.day').show();
} else {
$('.day').hide();
}
});
The trick here is to use the rails date select option :with_css_classes on the date select, so that it looks like this:
<%= f.date_select :date_value, :order => [:month, :day, :year], :with_css_classes => true, class: 'date-select' %>
This causes each included field to get a class corresponding to its name, hence our reference to '.day' up there.
The next important part, however, because he is using a gem called cocoon to add new elements that included date fields, we had to use some of their jquery event bindings to make sure that the new ones got the right action applied to them.
$('#container').on('cocoon:after-insert', function(e, insertedItem) {
if($('#instance').is(':checked')) {
$('.day').show();
} else {
$('.day').hide();
}
});
Technically, the $('.day').show() is not necessary, because it defaults to being shown, but this, to me, gets across the intent a little clearer.
I think my solution is a little bit messy, but hopefully it gives you an indication of my train of thought and give you something to build upon.
I have changed your categories to work with a radio button group because the select field is a bit weird for 2 elements (subjective I know), to change it back to a select form,simply keep your code as is, but you will need to check the value of the select dropdown using jQuery .change() or some other vanilla Javascript way...
You haven't provided any controller names, so I didn't know how to name my JS file, but hopefully you know how to integrate.
IMO, I'm not sure why this needs AJAX, so maybe you can explain to me where that comes in.
_form.html.erb
<%= Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:category, c) %>
<%= label(c, c) %>
<% end %>
_results_fields.html.erb
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-my' %>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-mdy' %>
vanilla.js
$(document).ready(function(){
$('.date-select-mdy').hide();
$('.date-select-mdy').attr("disabled", true);
$('input[name$=\category\']').click(function() {
var target_value;
target_value = $(this).val;
if (target_value === 'Monthly Average') {
$('.date-select-my').show();
$('.date-select-mdy').hide();
$('.date-select-my').attr("disabled", false);
return $('.date-select-mdy').attr("disabled", true);
} else {
$('.date-select-my').hide();
$('.date-select-mdy').show();
$('.date-select-my').attr("disabled", true);
return $('.date-select-mdy').attr("disabled", false);
}
});
});
a_little_bit_of_coffee_because_i_dislike_js.coffee
$->
$('.date-select-mdy').hide()
$('.date-select-mdy').attr("disabled",true)
$('input[name$=\category\']').click ->
target_value = $(this).val
if target_value == 'Monthly Average'
$('.date-select-my').show()
$('.date-select-mdy').hide()
$('.date-select-my').attr("disabled",false)
$('.date-select-mdy').attr("disabled",true)
else
$('.date-select-my').hide()
$('.date-select-mdy').show()
$('.date-select-my').attr("disabled",true)
$('.date-select-mdy').attr("disabled",false)
return

How to add/remove a group of fields using jQuery in a multi-step Rails 3 form?

I have a Rails 3 app with a multi-step form that I developed using this railscast: http://railscasts.com/episodes/217-multistep-forms
In the 3rd step(not the last step) of my form, I have a group of fields, called "Audience", which contains 4 select boxes.
Using Jquery, I have "add" and "remove" links next to this group of fields, so that I can have multiple "Audiences" in the form.
So for example, I start off with 1 Audience. If I click "add", then I have another Audience for a total of 2 Audiences (2 groups of fields). However, if I click on "remove", then that Audience will be removed from the form, and I'll be left with 1 Audience (1 group of fields) again.
This Audience form is nested. I used the nested form gem for this: https://github.com/ryanb/nested_form/
My problem is that no matter what I try, this Audience portion of the form never seems to work correctly. Right now, when the Audience form page first loads, the "remove" link doesn't appear at all, and every time I click the "add" link, 2 groups of fields are added instead of just 1. When I go to another page, and then come back to the Audience form again, then the "remove" link reappears, but the "add" link still does the same thing. Every time I go back to the page, more fields are added without me even clicking on the "add" link. In addition, I set a limit to the number of fields, but that doesn't work either.
I've spent the better part of a week on this problem, and I still can't figure it out. My Jquery skills are not wonderful, but I can do the basics. I've repeatedly asked for suggestions, but they never work. I'm desperate at this point...I already started banging my head against the wall a few days ago.
I have a good demonstration of what I want here, just replace "beets" with a group of fields: http://jsfiddle.net/beehive/8zJr6/
Any suggestions for a solution to this would be greatly appreciated. Maybe I should just go with a different approach entirely?
application.js
$(document).ready(function() {
// Nested Audience form
var x = $('#audiencefields');
var i = $('#audiencefields p').size() + 1;
$('#addlink').live('click', function() {
if ($(".item", x).length < 3) {
$('<p class="item" id="audiencecontainer">beets '+ i +'#removelink').appendTo(i);
i++;
}
return false;
});
$('#removelink').live('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
_audience_step.html.erb
<div class="uploadcontent">
<h1 class="uploadtitle">select your audience</h1>
<div id="audiencefields">
<p id="audiencecontainer">
<%= f.fields_for :audiences do |audience_form| %>
<ul class="uploadformlist">
<li>
<%= audience_form.label :number_of_people, "Size" %><br />
<%= audience_form.collection_select :number_of_people, Audience::PEOPLE, :to_s, :to_s, :include_blank => true %>
</li>
<li>
<%= audience_form.label :gender %><br />
<%= audience_form.collection_select :gender, Audience::GENDERS, :to_s, :to_s, :include_blank => true %>
</li>
<li>
<%= audience_form.label :age %><br />
<%= audience_form.collection_select :age, Audience::AGES, :to_s, :to_s, :include_blank => true %>
</li>
<li>
<%= audience_form.label :ethnicity %><br />
<%= audience_form.collection_select :ethnicity, Audience::ETHNICITIES, :to_s, :to_s, :include_blank => true %>
</li>
</ul>
<%= audience_form.link_to_remove "Remove this audience", :id => "removelink" %>
<% end %>
</p>
</div>
<p><%= f.link_to_add "Add another audience", :audiences, :id => "addlink" %></p>
</div>
audience.rb
class Audience < ActiveRecord::Base
attr_accessible :age, :ethnicity, :gender, :number_of_people
belongs_to :upload
#validates_presence_of :age, :ethnicity, :gender, :number_of_people
PEOPLE = ['5', '10', '25', '50', '75', '100']
GENDERS = ['Male', 'Female']
ETHNICITIES = ['Caucasian/White', 'African-American/Black', 'Latin/Hispanic', 'Asian', 'Indian', 'Middle-Eastern', 'Native American']
AGES = ['0-2', '3-5', '6-12', '13-17', '18-29', '30-39', '40-49', '50-59', '60+']
end

How reset multiple scroll down selected menus

I've 2 scroll down menus like
<%= f.label :term_id, "TERM *"%>
<br>
<%= f.collection_select :term_id, Term.order(:id), :id, :name, include_blank: true %>
<br>
<%= f.label :lesson_id, "LESSON *" %>
<br>
<%= f.grouped_collection_select :lesson_id, Term.order(:name), :lessons, :name, :id, :name, include_blank: "Ders Seçiniz" %>
and the javascript code is like that
jQuery ->
lessons = $('#demand_lesson_id').html()
$('#demand_term_id').change ->
term = $('#demand_term_id :selected').text()
options = $(lessons).filter("optgroup[label='#{term}']").html()
if options
$('#demand_lesson_id').html(options)
else
$('#demand_lesson_id').empty()
I need to reset when I click to reset button. but all forms elements are cleaned except lessons group collection.
How can I manage it?
The form reset button should restore all your select's default options. But if you need something to override whatever it is overriding the reset button behaviour, here's some plain old jQuery (Sorry, but I'm not familiar with CoffeeScript).
See it at the following jsFiddle
$(function(){
// reset button click
$('#myReset').click(function(){
// cycle through each option and restore to default
$('#myForm select option').each(function(){
$(this).prop('selected', $(this).prop('defaultSelected'));
});
});
});

Categories

Resources