如何根据前一个选择框中的值过滤选择框?

时间:2015-01-26 14:15:34

标签: jquery

在我的网络应用程序中,我有以下两个选择框:

<select id="project">
  <option value="">None</option>
  <option value="33">Some Project</option>
  <option value="32">Best project ever</option>
  <option value="31">Another project</option>
</select>

<select id="person">
  <option data-project_ids="[31, 33]" value="65">John</option>
  <option data-project_ids="[31]" value="66">Liz</option>
  <option data-project_ids="[]" value="67">Jim</option>
</select>

使用jQuery,如何根据#person选择框中选择的值(= project_id)过滤#project个选项?

如果没有选择项目,则应显示所有人员。

也可能会在页面加载时预先选择项目。

1 个答案:

答案 0 :(得分:8)

选项1

使用indexOfWorking example

JS

function CheckProjects() {
    var curProject = $('#project').val(); //Get the current select project
    $('#person option').each(function () { //Loop through each option
        var arrProjects = $(this).attr('data-project_ids'); //Put the array of projects in a variable
        if (arrProjects.indexOf(curProject) > -1) { //If current project ID is in array of projects
            $(this).show(); //Show the option
        } else { // Else if current project ID is NOT in array of projects
            $(this).hide(); //hide the option
        }
    });
}

CheckProjects(); //Call the function when we run the page
$('#project').on('change', function() { //When we change the project, call the function
    CheckProjects();
});

选项2

(感谢T.J.Crowder提供的有用评论)

使用$.inArrayWorking example

JS

function CheckProjects() {    
    var curProject = parseInt($('#project').val()); //Get the current select project and make it an integer
    $('#person option').each(function () { //Loop through each option
        var arrProjects = JSON.parse($(this).attr('data-project_ids')); //Put the array of projects in a variable
        if ($.inArray(curProject, arrProjects) > -1) { //If current project ID is in array of projects
            $(this).show(); //Show the option
        } else { // Else if current project ID is NOT in array of projects
            $(this).hide(); //hide the option
        }
    });
    //this is to stop the dropdown displaying a hidden option on project change
    if ($('#person :selected').is(':hidden')) { //If the selected person is now hidden
        $('#person').val(''); //Reset the person select box
    }
}

CheckProjects(); //Call the function when we run the page (at bottom of page, or within $(document).ready or something similar)
$('#project').on('change', function() { //When we change the project, call the function
    CheckProjects();
});