Option 1
Using indexOf: Working 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();
});
Option 2
(Thanks to helpful comment by T.J.Crowder)
Using $.inArray
: Working 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();
});