Search code examples
javascriptjqueryruby-on-railsradio-buttonsimple-form

How to render input form based on radio button checked in rails simple form


I have two options for a radio button and I want to display an input form based on which radio button is clicked using JQuery. This is the simple form input for my radio buttons

<div class="form-group">
  <label class="col-md-1 control-label"></label>
  <div class="col-md-9">
    <%= f.input :job_application_type, as: :radio_buttons, collection: [['Apply By Email', 'Email'], ['Apply By Url', 'Url']], :label => "How to apply" %>
 </div>
</div>

If the first radio button is checked, I want to display this input

<div class="form-group show-job-email" style="display:none">
<label class="col-md-1 control-label"></label>
<div class="col-md-9">
  <%= f.input :job_email, :label => "Job Email" %>
</div>

If it's the second radio button, I would like to display this input

<div class="form-group show-job-url" style="display:none">
<label class="col-md-1 control-label"></label>
<div class="col-md-9">
  <%= f.input :job_url, :label => "Job Url" %>
</div>


Solution

  • Just bind the change event to your radio buttons like so, and add/remove a specific class for your form groups:

    $(document).ready(function() {
      $('input[type="radio"][name="job_application_type"]').change(function() {
          if (this.value == 'Email') {
              $('.form-group.show-job-url').addClass('form-group--inactive');
              $('.form-group.show-job-email').removeClass('form-group--inactive');
          }
          else if (this.value == 'Url') {
              $('.form-group.show-job-url').removeClass('form-group--inactive');
              $('.form-group.show-job-email').addClass('form-group--inactive');
          }
      });
    });
    

    Remove your stying from form groups and place it under this form-group--inactive class in your css file.

    .form-group--inactive { display: none; }