1

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">&times;</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");
    }
  });
}
Vineetha
  • 11
  • 2
  • you want to add country (country received from your json) in your select tag? – Frenchy Feb 15 '21 at 09:00
  • Is this your issue: *I am unable to set the value of the country in the select2 dropdown* ? All the other parts seem completely superfluous to this part. ie this line: `$('#country').val("1").trigger("change");`? – freedomn-m Feb 15 '21 at 10:17
  • Your code, as provided, works fine: `https://jsfiddle.net/4fbpjg8w/` however, there's some subtle parts of your question that make it seem this is not the issue 1) this doesn't work for you. 2) you tagged [bootstrap-modal] (without modal code, so I initially removed it) 3) you mention *in the bootstrap* - do you mean "in the bootstrap modal dialog"? If so, you need to add a bit of code to your select2 so it works in a modal. This should fix your problem: https://select2.org/troubleshooting/common-problems – freedomn-m Feb 15 '21 at 10:21
  • i am retrieving country_id from city database linked to the city and setting the value to show as the selected country for the city in the dropdown (this dropdown has the countries from the country table) – Vineetha Feb 15 '21 at 13:19
  • @freedomn-m - For some reason this is not working for me. I did check your jsfiddle. Other than the change that my dropdown is actually inside a modal box, there's no change. but not working for me. i am passing the response value retrieved from database using a ajax php call $('#country').val("1").trigger("change"); – Vineetha Feb 15 '21 at 13:22
  • added full code of modal box – Vineetha Feb 15 '21 at 13:29

1 Answers1

0

inside your ajax, you add option following your country like that (i suppose response.country is country, either you adapt):

function(response){
   var idx=1;
   countries=[];
    for(var i = 0;i< response.length;i++){
       if(countries.includes(response.country) continue;//country already in option?
       countries.push(response.country);//i keep the country in array
       $("#country").append(new Option(response.country, idx++));//add option to select
    }
     $("#country").select2();//initialize the select2
    
}
Frenchy
  • 16,386
  • 3
  • 16
  • 39