Rails 3 - Checkbox dependant of radio button selection - javascript

I need a solution to hide/show a checkbox depending a radio button selection. I tried different solution found here and there but I can make them work.
CONTEXT:
I have a pool of contact persons that can be associated to a business. A user can select multiple contact persons but MUST select a primary contact person. So I have a radio button group whit all the contact persons to select the primary contact, and I have a checkbox group with again all the contact persons to select the "other" contacts.
NEED:
Now, what I like to do is that when the user select the primary contact in the radio button group, this contact will be removed from the "other contact" checkbox group, so the user cannot select the same contact twice. I can use JQuery as well as plain JavaScript.
CONSTRAINT:
The radio button group, as well as the checkbox group, are dynamically created using Rails Tag helper. So it's kind of tricky for the ids and name of the elements. Also, there is a has_many :trough between business and contact.
So for the radio button, I have:
<% #contacts.each do |contact| %>
<li><%= radio_button_tag 'primary_contact', contact.id, #primary_contact == contact, :class => 'radio'%> <%= contact.name %>, <%= contact.contact_type.name %></li>
<% end %>
And for the checkbox group, I have:
<%= hidden_field_tag 'business[contact_ids][]', "" %>
<% #contacts.each do |contact| %>
<li><%= check_box_tag 'business[contact_ids][]', contact.id, #business.contacts.include?(contact), :class => 'radio' %> <%= contact.name %>, <%= contact.contact_type.name %></li>
<% end %>
Any suggestion about other design (using radio buttons and checkboxes...) to achieve my goal are very welcome.
Thanks
Alain

<li><%= radio_button_tag ... :id => "#{contact.id}", :onclick => 'removeFromOtherList(this.id);' %><%= " #{contact.name}, #{contact.contact_type.name}" %></li>
This way you have the contact ids for the HTML tag id. Onclick it will remove\disable the other contact
Do the same for the other contacts
...<%= check_box_tag ... :class => 'radio', :id => "otherContact#{contact.id}" %> ...
Then we can remvoe the correct contact from the other list
function removeFromOtherList(contactId) {
$("#otherContact"+contactId).parent().remove(); //to remove the LI
}
Demo
Edit:
One way to do it is use show/hide and keep track of the last selected radio
var lastSelectedRadioId = null;
function removeFromOtherList(contactId) {
$("#otherContact"+contactId).parent().hide();
if(lastSelectedRadioId ){
$("#otherContact"+lastSelectedRadioId ).parent().show();
}
lastSelectedRadioId = contactId;
}
Demo

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

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

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?

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

Select/Deselect multiple check boxes using Jquery in loop(Rails)

I working on RoR, I have a two loops inside that i am displaying records with check boxes.
<%= form_tag some_path, :method => 'post' do %>
For loop
<%= check_box_tag 'ids[]', value %> Name
For loop
<%= check_box_tag 'ids_of_second_loop[]', value %> Name
end
end
<%= submit_tag "Next" %>
<% end %>
Now i wanted to apply a jquery where i can select/ deselect the checkboxes.
I can do if its not in the loop straight forward,
I am referring below link for implementation,
link
Loop Output...
How to achieve it...
I would do something like
<%= form_tag some_path, :method => 'post' do %>
For loop
<%= check_box_tag 'ids[]', value, class: 'parent' %> Name
<div class='children'>
For loop
<%= check_box_tag 'ids_of_second_loop[]', value %> Name
end
</div>
end
<%= submit_tag "Next" %>
<% end %>
note that "div class='children'" after the checkbox and the class "parent" on all parent checkboxes
then, javascript
$('input.parent').on('change',function(){
$(this).next('.children').find('input[type=checkbox]').prop('checked',$(this).prop('checked'));
})
it searches the next div with class 'children' after the clicked checkbox, then, it searches all inputs with type=checkbox inside that div, and sets the prop "checked" to the value returned by the current input clicked
Working fiddle :
$("#button").click(function () {
if($("#test")[0].checked)
{
$("#test")[0].checked = false;
}
else
{
$("#test")[0].checked = true;
}
});
http://jsfiddle.net/q8wvv1ky/

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

Categories

Resources