Advertisement
Virajsinh

Select2 Independ Search Without Ajax

Jun 24th, 2024 (edited)
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.48 KB | Source Code | 0 0
  1.     $('employee_id').select2();
  2.  
  3.     // PHP-generated employee data
  4.     const employees = {!! $employeeDataJson !!};
  5.  
  6.     // Function to filter and populate employee dropdown
  7.     function filterEmployees() {
  8.         const type = $('#emp_type').val();
  9.         const department = $('#department').val();
  10.  
  11.         let filteredEmployees = employees;
  12.  
  13.         if(type){
  14.             filteredEmployees = filteredEmployees.filter(employee => employee.employee_type === type);
  15.         }
  16.  
  17.         if(department){
  18.             filteredEmployees = filteredEmployees.filter(employee => employee.department_type === department);
  19.         }
  20.  
  21.         // Clear current options
  22.         $('#employee_id').empty().append('<option value="">Select Employee</option>');
  23.  
  24.         // Add filtered options
  25.         filteredEmployees.forEach(employee => {
  26.             // $('#employee_id').append(new Option(employee.name, employee.id));
  27.             var newOption = $('<option>');
  28.             newOption.attr('value', employee.id); // Set the value attribute
  29.             newOption.text(employee.name); // Set the text content
  30.             newOption.attr('data-department_type', employee.department_type);
  31.             newOption.attr('data-employee_type', employee.employee_type);
  32.             newOption.attr('data-shift_start', employee.shift_start);
  33.             newOption.attr('data-shift_end', employee.shift_end);
  34.             $('#employee_id').append(newOption);
  35.         });
  36.  
  37.         // Refresh Select2
  38.         $('#employee_id').trigger('change');
  39.     }
  40.  
  41.     // Event listeners
  42.     $('#emp_type, #department').on('change', filterEmployees);
  43.  
  44.     // Initial population
  45.     filterEmployees();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement