Reputation: 13
I am working on a personal project where I want users to be able to create profiles (I am using Devise to handle users). These can either be public or private, whereby public profiles require more input fields than private profiles. Is there any way I can cause these additional form fields to only appear if the user chooses his profile to be public?
I tried looking on StackOverflow and previous threads on here but couldn't find anything. I saw a few suggestions for the Cocoon gem but couldn't get that to work.
<%= simple_form_for(@User, url: registration_path(@User)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :first_name, required: true, autofocus: true %>
<%= f.input :email,
required: true,
input_html: { autocomplete: "email" }%>
<%= f.input :public, required: false, label: "Enable public profile?" %>
## Ideally the following two-fields would only show if public is clicked
## Best case they would be required fields if this happens and not required if
it does not
<%= f.input :linkedin_link, required: false, label: "Linked-In Profile Link" %>
<%= f.input :photo, as: :file, label: "Profile Picture", accept: "image/*", hint: "Why not use your Linked-In profile picture? (png and jpg only)" %>
<%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), input_html: { autocomplete: "new-password" } %>
<%= f.input :password_confirmation, required: true, input_html: { autocomplete: "new-password" } %>
<%= f.button :submit, "Sign up", class: "btn-success btn-full-width" %>
</div>
<% end %>
Looking forward to learning something new :) Thanks a lot for your help!
Upvotes: 0
Views: 228
Reputation: 13
Managed to solve it with this.
JS:
$(function () {
$('div[name="showthis"]').hide();
//show it when the checkbox is clicked
$('input[type="checkbox"]').on('change', function () {
if ($(this).prop('checked')) {
$('div[name="showthis"]').fadeIn();
} else {
$('div[name="showthis"]').hide();
}
});
});
HTML:
<div class="form-inputs">
<%= f.input :first_name, required: true, autofocus: true %>
<%= f.input :email, required: true, input_html: { autocomplete: "email" }%>
<%= f.input :public, required: false, label: "Enable public profile?" %>
<div name="showthis">
<%= f.input :linkedin_link, required: false, label: "Linked-In Profile Link" %>
<%= f.input :photo, as: :file, label: "Profile Picture", accept: "image/*", hint: "Why not use your Linked-In profile picture? (png and jpg only)" %>
</div>
<%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), input_html: { autocomplete: "new-password" } %>
<%= f.input :password_confirmation, required: true, input_html: { autocomplete: "new-password" } %>
<%= f.button :submit, "Sign up", class: "btn-success btn-full-width" %>
</div>
Upvotes: 1