Toggle fields based on radio button selection with simple_form, haml, and jquery

I have a radio button in my form. If true is selected, I would like to show an additional field. If false, I would like the additional field hidden. I have tried several possible solutions I found on SO but none seem to be working.

In my form:

%fieldset
  %legend
    Visa & Passport
  .form-group
    = f.input :work_visa, as: :radio_buttons, label: "Do you have a work visa?", collection: [['Yes', true], ['No', false]], checked: true, item_wrapper_class: 'radio-inline', wrapper_html: { id: 'work-visa'}
    = f.input :visa_exp_date, label: 'Visa Expiration Date', item_wrapper_class: 'form-inline', class: 'col-xs-4', wrapper_html: { id: 'work-visa-exp'}

At the bottom of the page:

:javascript  
  $('#work-visa-exp').show();    
  $('input[type=radio]').on("change", function(){
    if($(this).prop('id') == "work-visa") {
      $('#work-visa-exp').toggle();
    }
  });

I am pretty sure the error is in my JS. If I comment out everything but $('#work-visa-exp').show(); and change .show() to .hide(), the field is hidden as expected.

1 answer

  • answered 2018-02-13 03:40 Eddie

    Based on your description, you need a checkbox and not a radio button.

    Please check below:

    $(document).ready(function() {
      $('#work-visa-exp').hide();
      $('input[type=checkbox]').on("change", function() {
        if ($(this).prop('id') == "work-visa") {
          $('#work-visa-exp').toggle();
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" name="vehicle" id="work-visa" value="">
    <input type="text" name="vehicle" id="work-visa-exp" value="">


    If you are using other radio buttons (different kind of visas). Then you can try below.

    With this one you have to check the value of the selected radio buttons and not the id.

    $(document).ready(function() {
      $('#work-visa-exp').hide();
      $('input[type=radio]').on("change", function() {
        if ($(this).val() == "work-visa") {
          $('#work-visa-exp').show();
        } else {
          $('#work-visa-exp').hide();
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="radio" name="visa" value="work-visa"> Work Visa <input type="text" name="vehicle" id="work-visa-exp" value=""> <br />
    <input type="radio" name="visa" value="other-visa"> Other Visa <br />
    <input type="radio" name="visa" value="some-visa"> Some Visa <br />