Jquery - optgroup hide()在点击之前不刷新下拉列表

时间:2017-06-07 12:48:36

标签: javascript jquery

我试图根据从单选按钮中选择的值在下拉列表中隐藏optgroup。这一切都很好,除了下拉列表没有立即刷新 (它可能已经有一个来自之前的预选值,而不管它落入的optgroup

$('input[id*="school_type"]').on("change",function(){
        if ($(this).is(':checked')) {
          var selectedVal=($(this).next().text()); 
          $("#id_school_sub_type > optgroup").hide(); 
          $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
        }
    });

JS Fiddle

仅当用户点击后续下拉列表时,才会隐藏或显示optgroup。是否有可能刷新"它立刻?

1 个答案:

答案 0 :(得分:1)

隐藏之前删除该项目的选择:

$('input[id*="school_type"]').on("change",function(){
    if ($(this).is(':checked')) {
      var selectedVal=($(this).next().text()); // using next() so we can get the verbose value from the <span> next to <input>
      $("#id_school_sub_type").val('');
      $("#id_school_sub_type > optgroup").hide(); 
      $('#id_school_sub_type > optgroup[label="'+selectedVal+'"]').show();
    }
});

如果想要进行选择,请添加以下行:

$("#id_school_sub_type").val($('#id_school_sub_type optgroup[label="'+selectedVal+'"] option:first').val());

Fiddle