Mel
Mel

Reputation: 2715

Rails Simple Form Bootstrap Javascript

I have a rails 4 app with bootstrap and simple form.

I have a simple form for datum.

It has a primary question, which if answered true, requires a follow up question. I want to hide the follow up question until the first question is answered as true.

I have defined a separate CSS class for the label above the follow up question (survey-link-data) so that the label is hidden and shown with the input field. This JS is incorrect - it doesn't hide at then show as I had hoped.

Please can you see what I've done wrong? Thank you.

These are my two simple form for (@datum) questions:

<%= f.input :survey, :as => :boolean, :label => false, inline_label: 'Do you need survey responses?'  %>
<br><br>


    <%= f.input :survey_link, label: 'Where is your survey?', :label_html => { :class => 'data-survey-link' }, placeholder: 'Include a link to your survey', :input_html => {:style=> 'width: 650px; margin-top: 20px',  class: 'response-project'} %>

This is my JS script:

<script>
$(function() {
    // Hide the survey_link input

    $('input[name="datum[survey_link]"]').hide();
    $('.data-survey-link').hide();
    // When the survey checkbox changes
    $('input[name="datum[survey]"]').change(function() {
         // If the survey checkbox is ticked
         if(this.checked) {
              // Survey checkbox was ticked - show the survey_link input
              $('input[name="datum[survey_link]"]')toggle(this.checked);
              $('.data-survey-link').show();

         } else {
              // Survey checkbox was unticked - hide the survey_link input
              $('input[name="datum[survey_link]"]').hide();
              $('.data-survey-link').hide();

         }
    });
});
</script>

Upvotes: 1

Views: 550

Answers (1)

Ernest
Ernest

Reputation: 8829

First of all, you are selecting, and hiding two elements (label and input), which is less efficient than just hiding/showing a wrapper (by default simple_form wraps input and label inside a special div tag). Let's give this wrapper a class:

<%= f.input :survey_link, wrapper_html: { class: 'survey-link-wrapper' } %>

I stripped the rest of the options for the simplicity of example.

You can initially hide it with CSS:

.survey-link-wrapper {
  display:  none;
}

Second, create a more efficient selector for first input:

<%= f.input :survey, input_html: { class: 'survey-checkbox' } %>

Then your javascript code becomes this:

<script>
$(function() {
    var $surveyLinkWrapper = $('.survey-link-wrapper');
    $('.survey-checkbox').change(function(e) {
         // If the survey checkbox is ticked
         if ( $(this).is(":checked") )  {
              // Survey checkbox was ticked - show the survey_link input
              $surveyLinkWrapper.show();
         } else {
              $surveyLinkWrapper.hide();
         }
    });
});
</script>

More clear and easier to read.

Upvotes: 1

Related Questions