To do: Add a city under a country. Then attempt to edit the city record. I have: City name as a textbox and Country as a Select2 dropdown in the bootstrap modal which is accessed using a Edit button on the page.
Issue - I am unable to set the value of the country in the select2 dropdown retrieved from database using ajax call. I tried all possible combinations to set value. I am able to set value if its a normal dropdown box, but not when it is a select2 box.
This is the html of the select 2 box in the bootstrap
<div class="modal fade" id="edit">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick = "location.reload(true);">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title"><b>Edit City</b></h4>
</div>
<div class="modal-body">
<form class="form-horizontal" method="POST" action="city_edit.php">
<input type="hidden" class="catid" name="id">
<input type="text" name="cityid" id="cityid" hidden>
<div class="form-group">
<label for="name" class="col-sm-3 control-label">City</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="cityname" name="cityname" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Country</label>
<div class="col-md-8">
<select data-plugin-selectTwo class="form-control" name="country" id="country" required>
<option value = "">Select Country</option>
<?php
$conn = $pdo->open();
try{
$stmt = $conn->prepare("SELECT country_id,country FROM country where del_flg = 'N' and status = 1");
$stmt->execute();
foreach($stmt as $row)
{
$countryid = $row['country_id'];
$country = $row['country'];
echo "
<option value='".$countryid."'>".$country."</option>
";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo->close();
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal" onclick = "location.reload(true);"><i class="fa fa-close"></i> Close</button>
<button type="submit" class="btn btn-success btn-flat" name="edit"><i class="fa fa-check-square-o"></i> Update</button>
</form>
</div>
</div>
</div>
JQUERY:
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
$(document).on('click', '.edit', function(e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
function getRow(id){
$.ajax({
type: 'POST',
url: 'city_row.php',
data: {id:id},
dataType: 'json',
success: function(response){
$("input[type=text][name=cityname]").val(response.city);
$('#country').val("1").trigger("change");
}
});
}