如何在选择另一个下拉框时清除已选中的文本?
Hey there, I get exactly what's going on here—when you switch the department dropdown, the employee dropdown sticks with its previously selected text instead of resetting to the default "Select Employee" option. Let's get this sorted out quickly!
What's Causing the Issue
Right now, your AJAX call updates the list of options in the employee dropdown, but it doesn't touch the existing selected value. So even though the options change, the old selected text stays visible until you manually pick a new employee.
The Simple Fix
Just add one line to your jQuery success handler to explicitly reset the employee dropdown after updating its options. Here's the modified script:
$(document).ready(function(){ $('#department').change(function(){ var department = $(this).val(); $.ajax({ url: "<?php echo base_url();?>admin/payroll/fetch_employee", method: "POST", data: {department_id: department}, success: function(data) { $('#employee').html(data); // This line resets the dropdown to the empty default option $('#employee').val(''); } }); }); });
Why This Works
$('#employee').html(data)replaces the old employee options with the new ones fetched from your backend.$('#employee').val('')sets the dropdown's value back to the empty option, which matches the default<option value="">Select Employee</option>you're generating both in the initial HTML and your model's output. This instantly clears any previously selected text.
Quick Validation Check
Double-check that your empty default option has a value of empty string (value="") in both places:
- Initial employee dropdown:
<option value=""><?= lang('select') . ' ' . lang('employee') ?></option>✅ - Model-generated options:
<option value="">Select Employee</option>✅
This matches exactly what we're setting with .val(''), so the reset will work perfectly every time you switch departments.
内容的提问来源于stack exchange,提问作者Kelly

