I have a car "make" and car "model" tables in my database. When I echo car "makes" it works properly. However, I want the car "model" drop-down to appear with ajax based on selected "make", it does not work in the view
However, all information that I need, appears on the console's network tab.
Where can be the problem? Here is my ajax code:
<script type="text/javascript">
var base_url = "<?php echo base_url();?>";
$(document).ready(function() {
$('select[name="make"]').on('change', function() {
var makeid = $(this).val();
if(makeid) {
$.ajax({
url: base_url + 'myform/ajax/'+makeid,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="model"]').empty();
$.each(data, function(key, value) {
$('select[name="model"]').append('<option value="value.id">'+ 'value.title' +'</option>');
});
}
});
}else{
$('select[name="model"]').empty();
}
});
});
</script>
Here is the view:
<?php $attributes = array( 'name' => 'addcar', 'id' => 'addcar'); ?>
<?php echo form_open_multipart('cars/create', $attributes); ?>
<div class="form-group label-floating">
<label class="control-label">
Марка
<small>*</small>
</label>
<select id="make" name="make" class="selectpicker" data-style="select-with-transition" required="true">
<option value=""></option>
<?php foreach($makes as $make): ?>
<option value="<?= $make['id']; ?>"><?= $make['maketitle']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group label-floating">
<label class="control-label">
Модель
<small>*</small>
</label>
<select id="model" name="model" class="selectpicker" data-style="select-with-transition" required="true">
</select>
</div>
</form>
You're not writing your values correctly, and you need to match the properties from the objects in your response to what you're trying to output:
$('select[name="model"]').append('<option value="value.id">'+ 'value.title' +'</option>');
should be
$('select[name="model"]').append('<option value="' + value.id + '">'+ value.modeltitle +'</option>');
You are appending to select element, but indeed you need to insert into it. Just get the first (option) element inside select and then append to that, something like this:
<select>
<option id="firstOption">First Option</option>
</select>
$("#firstOption").append(...)
And by the way, why value.title is inside quotes ?
+ 'value.title' +
I have found a solution to my question. As I use "Creative Tim" admin dashboard, they have their own classes. And when I removed class="selectpicker" from the select part it worked. Actually, I don't know what is the connection between them?