Hari Prakash Hari Prakash - 1 year ago 62
jQuery Question

Rails JS conditionally display div based on the radio button selected

$('.domestic_select, .abroad_select').on('click', function(){
if($(this).val() == "true") {
else {

= f.label :pin_code,"Pin Code", class: "col-sm-3 control-label text-right"
= f.text_field :pin_code, autofocus: true, class: "col-sm-3"
%div{id: 'state_field'}
= f.label :state,"State", class: "col-sm-3 control-label text-right"
= f.select(:state, options_for_select(State.collect_state),{},{class: "selectpicker col-sm-3", id: "myselect", prompt: "Select State", "data-live-search": "true"})
%div.hide{id: 'country_field'}
= f.label :country,"Country", class: "col-sm-3 control-label text-right"
= f.select(:country, Country.collect_country,{}, {class: "selectpicker add_class_country dropdown_country col-sm-3", title: "select country", "data-live-search": "true"})


Here I've hidden the country div, so that the state field is being displayed initially. when clicked the abroad option the "country div" should be displayed and "state div" should be hided

But what I got is both state and country fields are hidden after selecting the abroad option.

Answer Source

How have you hidden #country_field initially. display: none;? You need to make sure that you are using display: none and not visibility: none; or some other styling as jquery uses, display: none/block; to hide and show.

$('.domestic_select').on('change', function(){
  if($(this).is(':checked')) {
    $('#customer_goods, #state_field, #change_resident').removeClass('hide');

$('.abroad_select').on('change', function(){
  if($(this).is(':checked')) {
    $('#customer_goods, #state_field, #change_resident').addClass('hide');