[eluser]ninjayan[/eluser]
I also have a problem in dynamic dropdown. Here's my code
view
Code:
<select name="source_type" id="source_type">
<option value="">Source Type</option>
<option value="Internal">Internal</option>
<option value="External">External</option>
</select>
<select name="source_location" id="source_location">
<option value="">Source Location: Office/Barangay/NGA</option>
</select>
$('#source_type').change(function(){
$.ajax({
url: "get_sources_location",
type: 'POST',
async: false,
data: 'source_ref='+$(this).val(),
dataType: 'json',
success: function(data) {
console.log('okay!');
$("<option/>",{text:data.source_locations, value:data.source_locations}).appendTo("#source_location");
}
});
});
controller
Code:
$data = array('source_locations' => NULL);
$this->load->model('documents_model');
$data['source_locations'] = $this->documents_model->get_locations();
echo json_encode($data);
model
Code:
$query = $this
->db
->select('location')
->where('classification', $this->input->post('source_ref'))
->get('sources_location');
$data = array();
foreach ($query->result() as $row)
{
$data[] = $row->location;
}
return $data;
Goal: to populate
#source_location based on
#source_type
What is the output of my code: Only returns the last data.
Internal have 22 records on database
External have 2 records on database
-----
*Currently reading the link given above
UPDATE
Solved. Solution
Code:
$('#source_type').change(function(){
$.ajax({
url: "get_sources_location",
type: 'POST',
async: false,
data: 'source_ref='+$(this).val(),
dataType: 'json',
success: function(data) {
$("#source_location option").remove();
for (var i=0;i<data.length;i++) {
$("<option/>",{text:data[i], value:data[i]}).appendTo("#source_location");
}
}
});
});