Hari Prakash Hari Prakash - 4 months ago 22
jQuery Question

Rails JS conditionally display div based on the radio button selected

$('.domestic_select, .abroad_select').on('click', function(){
alert($(this).val());
if($(this).val() == "true") {
$('#customer_goods').show();
$('#state_field').show();
$('#country_field').hide();
$('#change_resident').show();
}
else {
$('#change_resident').hide();
$('#customer_goods').hide();
$('#country_field').show();
$('#state_field').hide();
}
});


.fieldset
.row
.col-sm-12
= 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"})

%br


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

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');
    $('#country_field').addClass('hide');
  }
});

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