简体   繁体   中英

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.

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');
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM