简体   繁体   English

页面加载过滤器中与下拉列表1的数据值匹配的第二个下拉选项

[英]On page load filter second dropdown options that match data value of dropdown 1

I have this code that I am using to filter a second drop down based on the first drop down. 我有这段代码可用于根据第一个下拉列表过滤第二个下拉列表。 It works fine with the onChange method, what it does, it takes the value from the first drop down option selected, then finds and matches the options "data-value" in the second drop down to filter. 它可以与onChange方法一起正常工作,它的工作原理是,它从所选的第一个下拉选项中获取值,然后在第二个下拉列表中查找并匹配选项“ data-value”以进行过滤。

$(document).ready(function() {
  // get first dropdown and bind change event handler
  $('#p-city').change(function() {
    // get optios of second dropdown and cache it
    var $options = $('#p-nhb')
    // update the dropdown value if necessary
    .val('')
    // get options
    .find('option')
    // show all of the initially
    .show();
    // check current value is not 0
    if (this.value != '0')
      $options
      // filter out options which is not corresponds to the first option
        .not('[data-val="' + this.value + '"],[data-val=""]')
        // hide them
        .hide();
  });
});

I'm using it on a form and the options will be saved, so how I can run the filter on page load if something is already selected? 我在表单上使用它,并且选项将被保存,因此如果已经选择了某些内容,如何在页面加载时运行过滤器?

Add $('#p-city').trigger('change'); 添加$('#p-city').trigger('change'); after $('#p-city').change(function() as shown in below code. This should work for sure, hope it does.i have tried the same with http://jsfiddle.net/heera/Gyaue/ jsfiddle with just selecting the first option by default and triggering the change event at end and it work $('#p-city').change(function() ,如下面的代码所示。这应该可以正常工作,希望能做到。我已经尝试使用http://jsfiddle.net/heera/Gyaue/ jsfiddle,默认情况下只选择第一个选项,最后触发change事件就可以了

$(document).ready(function() {
    // get first dropdown and bind change event handler
    $('#p-city').change(function() {
    // get optios of second dropdown and cache it
    var $options = $('#p-nhb')
    // update the dropdown value if necessary
    .val('')
    // get options
    .find('option')
    // show all of the initially
    .show();
    // check current value is not 0
    if (this.value != '0')
     $options
    // filter out options which is not corresponds to the first option
    .not('[data-val="' + this.value + '"],[data-val=""]')
    // hide them
    .hide();
    })

  $('#p-city').trigger('change');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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