How can we auto select ajax dropdown that is fetched using ajax from database table and populated in select box.
here is my code and it not seems to be working.
<script>
$(document).ready(function(){
$("#visitcountry").change(function(){
var countryfrom = "India";
var department = $(this).val();
var tablename = "country";
var res = dbnm.concat(department);
$('.overlay').show();
$.ajax({
url: '<?= base_url();?>index/countries',
type: 'post',
data: {dest:res},
dataType: 'json',
success:function(response){
console.log(response);
var len = response.length;
$("#countryby").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['cityname'];
$("#countryby").append("<option data-nation='"+name+"' value='"+name+"' "+ (countryfrom.trim() == name.trim()) ? 'selected' : '' +">"+name+"</option>");
//$("#countryby").append("<option data-nation='"+name+"' value='"+name+"'>"+name+"</option>"); -this option works and populate dropdown but i want auto selection based on countryfrom variable
}
$('.overlay').hide();
}
});
}).trigger('change');
});
</script>
this is my select box
<select class="countryby" name="countryby" id="countryby">
<option value="0">- Select -</option>
</select>
Note : i have passed php variable in "var countryfrom" and checked with single options but none of them worked, the issue is its not populating the dropdown.