JQuery将文本保留在应隐藏的选择框中

时间:2010-06-30 11:31:28

标签: jquery

我的表格如下:

<form action="search.php" method="post">
        <fieldset>
          <label for="level_one">Main category</label>
          <select name="level_one" id="level_one">
            <option value="0">All main categories</option>
                        <option value="7">Health</option>
                        <option value="11">Life</option>
                        <option value="8">Mind</option>
                        <option value="16">Relationships</option>
                      </select>
          <label for="level_two">Sub category</label>
          <select name="level_two" id="level_two">
            <option value="0" class="no_parent">All categories</option>
                        <option value="36" class="parent_id_7">Swine flu</option>
                        <option value="34" class="parent_id_7">Therapies</option>
                        <option value="40" class="parent_id_11">Bullying</option>
                        <option value="28" class="parent_id_11">Volunteering</option>
                        <option value="19" class="parent_id_8">Depression</option>
                        <option value="29" class="parent_id_16">Relationship problems</option>
                        <option value="37" class="parent_id_16">Separation and divorce</option>
                      </select>

          <input type="submit" value="Search" />
        </fieldset>
      </form>

使用JQuery我隐藏了第二个选择,然后当第一个选择更改时,JQuery查看选择并显示第二个选择,其中只包含相关项。 JQuery:

$(document).ready(function () {
  $('#level_two').hide()
  $('#level_one').change(function(){
   var current = $(this).val();
   if(current == 0) {
     $('#level_two').hide()
   } else {
     $('#level_two option').not('.no_parent').hide()
     $('.parent_id_'+current).show();
     $('#level_two').val("no_parent");  //gert g's addition :)
     $('#level_two').show()
   }
  });
});

除了一个小问题,这个工作正常。如果我在选择1中选择“健康”,选择2显示“猪流感”和“疗法”,然后我选择“治疗”,现在如果我选择生活在选择1,选择2显示正确的选项,除了选择默认文本尽管疗法选项是隐藏的,但仍然会说“疗法”。

有没有办法刷新文本以阻止这种情况发生。

此致

卢克

更新:我已将代码更新为正常工作,感谢@Gert G提供解决方案

更新:当前解决方案仅适用于FireFox :(

更新:我使用了@Paolo Bergantino解决方案的略微修改版本,该解决方案确实适用于chrome和FF,但尚未完成对所有浏览器的测试。

jQuery.fn.filterOn = function(radio, values) {
        return this.each(function() {
          var select = this;
          var options = [];
          $(select).find('option').each(function() {
            options.push({value: $(this).val(), text: $(this).text()});
          });
          $('#level_two').data('options', options);
          $('#level_one').change(function() {
            var options = $(select).empty().data('options');
            var haystack = values[$(this).val()];
            if($(this).val()==0){
              $('#level_two').hide().siblings('label[for="level_two"]').hide();
            } else $('#level_two').show().siblings('label[for="level_two"]').show();
            $.each(options, function(i) {
              var option = options[i];
              if($.inArray(option.value, haystack) !== -1) {
                $(select).append(
                $('<option>').text(option.text).val(option.value)
              );
              }
            });
          });
        });
      };
      $(document).ready(function () {
        $('#level_two').hide().siblings('label[for="level_two"]').hide();
        $(function() {
          $('#level_two').filterOn('#level_one', {
                        '7': ["35","12","17","32","33","46","30","31","15","36","34"],
                        '11': ["40","25","27","41","22","26","44","28"],
                        '8': ["19","21","20"],
                        '16': ["29","37","23"],
                        '10': ["14","43","45","39"],
                      }); //note there are way more values in these arrays as I did not enter the full form that I am using above just a short example
        });
      });

2 个答案:

答案 0 :(得分:2)

- 新版和改进版 -

<强>的jQuery

<script type="text/javascript">
  $(document).ready(function() {
    var LevelTwoData=[];
    LevelTwoData["7"]= { "36":"Swine flu",
                         "34":"Therapies" };
    LevelTwoData["11"]={ "40":"Bullying",
                         "28":"Volunteering" };
    LevelTwoData["8"]= { "19":"Depression" };
    LevelTwoData["16"]={ "29":"Relationship problems",
                         "37":"Separation and divorce" };

    $("#level_one").change(function() {
      $('#level_two').val("0");  // Set "All categories" as the selected option
      $('#level_two option:not(:first)').remove();  // Remove all previous values

      var LevelOneVal=$("#level_one").val();  // Grab main category value

      if(LevelTwoData[LevelOneVal]!=undefined) {  // If the category has subcategories
        $.each(LevelTwoData[LevelOneVal],function(Value,Text) {  // Loop through the subcateries and add them as options
          $('#level_two').append(
            $('<option></option>').val(Value).html(Text)
          );
        });

        $('#level_two').show();
      } else {
        $('#level_two').hide();
      }
    });
  });
</script>

<强> HTML

<form action="search.php" method="post">
  <fieldset>
    <label for="level_one">Main category</label>
    <select name="level_one" id="level_one">
      <option value="0">All main categories</option>
      <option value="7">Health</option>
      <option value="11">Life</option>
      <option value="8">Mind</option>
      <option value="16">Relationships</option>
    </select>
    <label for="level_two">Sub category</label>
    <select name="level_two" id="level_two">
      <option value="0">All categories</option>
    </select>

    <input type="submit" value="Search" />
  </fieldset>
</form>

- 原创(按照Luke最初的要求工作,但课程仅适用于Firefox) -

<强>的jQuery

<script type="text/javascript">
  $(document).ready(function () {
    $('#level_two').hide()
    $('#level_one').change(function(){
     var current = $(this).val();
     if(current == 0) {
       $('#level_two').hide()
     } else {
       $('#level_two option:not(.s0)').hide()
       $('#level_two').val("s0"); // Reset the option
       $('.s'+current).show();
       $('#level_two').show()
     }
    });
  });
</script>

<强> HTML

<form action="search.php" method="post">
  <fieldset>
    <label for="level_one">Main category</label>
    <select name="level_one" id="level_one">
      <option value="0">All main categories</option>
      <option value="7">Health</option>
      <option value="11">Life</option>
      <option value="8">Mind</option>
      <option value="16">Relationships</option>
    </select>
    <label for="level_two">Sub category</label>
    <select name="level_two" id="level_two">
      <option value="0" class="s0">All categories</option>
      <option value="36" class="s7">Swine flu</option>
      <option value="34" class="s7">Therapies</option>
      <option value="40" class="s11">Bullying</option>
      <option value="28" class="s11">Volunteering</option>
      <option value="19" class="s8">Depression</option>
      <option value="29" class="s16">Relationship problems</option>
      <option value="37" class="s16">Separation and divorce</option>
    </select>

    <input type="submit" value="Search" />
  </fieldset>
</form>

基本上你需要在刷新第一个选择时重置第二个选项。

答案 1 :(得分:0)

想一想,当你第二次更改第一个下拉列表时,你没有重新选择一个选项。所以它可能只是一个简单的“选定”问题 在更改活动结束时尝试这样的事情;

$('#level_two option.parent_id_'+current+':first').attr("selected", "selected").siblings().removeAttr("selected");

或者也可能这样做;

$('#level_two option').removeAttr("selected");