Ben Hawker
Ben Hawker

Reputation: 949

Rails select_tag - jQuery/JavaScript hide/show on change event

I have the following in a helper:

def cancellation_policies_options_for_elite(room)
  options_for_select( [ [t("cancellation_policies.standard"), "standard"], [t("cancellation_policies.moderate"), "moderate"], [t("cancellation_policies.strict"), "strict"], [t("cancellation_policies.elite"), "elite"], [t("cancellation_policies.super_elite"), "super_elite"]] )
end

Which specifies both the text rendered in the select menu but also the value (i.e. standard, moderate etc.)

In my view I then call:

<%= select_tag('selected_cancellation_policy_id', cancellation_policies_options_for_elite(@room), id: 'select-policy', class: 'input-xxlarge') %>

Below this I have the following divs:

<div id="moderate" class="policies" style="display:none">
  Moderate policy
</div>

<div id="strict" class="policies" style="display:none">
  Strict policy
</div>

<div id="elite" class="policies" style="display:none">
  Elite policy
</div>

$("#select-policy").on('change', function() {
  alert("It's working!");
  $('.policies').hide();
  $("#" + $(this).val()).show();
}

I have jQuery and jQuery UI in my project and it is all compiling correctly as many other jQuery elements are working. However I am getting no response at all from this function and completely missing why. Any ideas on this?

Upvotes: 0

Views: 245

Answers (1)

user3506853
user3506853

Reputation: 814

This should work:-

$(document).ready(function(){
    $('.policies').hide();
});

Then on change of select box do this:-

$(document).on('change', '#select-policy', function() {
    alert("It's working!");
    $('.policies').not("#" + $(this).val()).hide();
});

Also, in "Elite Policy" div, id should be "super_elite" instead of "elite". Because in select box cancellation elite value is "super_elite". And standard policy div is missing here.

Upvotes: 1

Related Questions