'fill select dropdown automatically and dynamically using ajax and jquery
i am working on adding items dynamically by the user and there are two dropdown lists in every item with two classes when i select a value from the first one it loads values based on my selection to the second list from the database it works but when i click to add a new item it appends the values to the previous one and i need it to load the values bases on the other selection only Here is my code:
<div class="col-2 cpfaculties">
<label for="cpfaculties-input" class="col-form-label">Faculties <span class="text-danger">*</span></label>
<select class="form-control cpfaculties-input" name="pfaculties[]" placeholder="Select ..." id="cpfaculties-input" required>
<option value="">Select ...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="col-3">
<label for="cpdepartment-input" class="col-form-label">Department <span class="text-danger">*</span></label>
<select class="form-control cpdepartment-input" name="pdepartments[]" placeholder="Select ....." id="cpdepartment-input" required>
<option value="">Select ...</option>
$('.rows').on('change','.cpfaculties-input', function(event){
var selectedItem = $(this).val();
var x = $(this).closest('div').next().find('select.cpdepartment-input');
$.ajax({
type:"GET",
url:"url",
data: {choice: selectedItem},
dataType: "JSON",
success: function(response){
$.each(response,function(key,value){
x.append('<option value = ' + value.department + '>' + value.department + '</option>');
console.log(value.department);
});
}
});
});
</select>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
