1

I have one initial dropdown, where I want to select a value:

<select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;">
<option value='' selected>Select and Index</option> 
<option value='3'>AIM</option>
<option value='1'>FTSE 100</option>
<option value='2'>FTSE 250</option>
</select>

When a different value is selected it runs the updateSector() function, which uses an ajax script to load all the sectors which are relevant for the selected category. The output from the page investment_sectors is then displayed in a tag on the page.

function updateSector(){
    
     <? if ($sectorID<>""){?>
      var sectorID = <?=$sectorID?>;
     <? }else{?>
      var sectorID = "";
      <?}?>
      
    var indexID = document.getElementById("indexID");
                var indexID = indexID.options[indexID.selectedIndex].value;
    
      var dataString = 'indexID=' + indexID +'&sectorID=' + sectorID;
      // AJAX code to submit form.
      $.ajax({
      type: "POST",
      url: "investment_sectors.php",

      data: dataString,
      cache: false,
      success: function(html) {
       //alert(html);
       document.getElementById("sector").innerHTML = html;
       
      }
      });

     }

This all works if I want to generate a standard select dropdown of the sectors. But as there are many sectors, I really want a select2 field.

Normally, if I was just including the select2 field in a standard page, I'd add this script to the bottom to load any passing values I want preselected. However, as the tag is empty until an option is selected and passed back, there is nothing to populate.

<script>
 $(document).ready(function() {
  $('.js-example-basic-single').select2();
 });
 $(document).ready(function() {
 
   var select2single = $('.js-example-basic-single').select2({
  placeholder: "Please Select",
   width: '400px',
  multiple: false,
   })
   select2single.val([<?=$sectorID?>]);
   select2single.trigger("change");
  
   
 }); 
</script>

Can anyone help me adapt my code to generate this select2 field, rather than a standard select dropdown?

Thanks

This is the code in the called investment_sector page:

$sectorID=$_REQUEST['sectorID'];
$indexID=$_REQUEST['indexID'];

switch ($indexID){
    case "1":
        $sectorlist = "FTSE";
        break;
    case "2":
        $sectorlist = "FTSE";
        break;
    case "3":
        $sectorlist = "AIM";
        break;
    default:
        $sectorlist = "";
}

$query = "SELECT * FROM tbl_sector WHERE sectorlist='".$sectorlist."' order by sector ASC";

$result = mysqli_query( $conn, $query )or showError( mysqli_query( $conn, $query ) );
$num_rows = mysqli_num_rows( $result );

echo "<select class=\"js-example-basic-single js-states form-control\" id=\"sectorID\" name=\"sectorID\">";

if ($sectorID==""){
    echo "<option value='' selected>Select a ".$sectorlist." sector</option> \n ";
}

$i = 0;
while ( $row = mysqli_fetch_array( $result ) ) {
  if ( $sectorID == $row[ 'sectorID' ] ) {
        echo "<option value='" . $row[ 'sectorID' ] . "' selected>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option> \n ";
     } else {
        echo "<option value='" . $row[ 'sectorID' ] . "'>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option>\n";
     }

  $i++;

}
echo "</select>";
petworthnick
  • 205
  • 2
  • 11
  • `showError( mysqli_query( $conn, $query ) )` < what is that supposed to do? If you meant to check for errors on the query, then that isn't the function for it, you want `mysqli_error($conn)`. You have a function called `showError()`? – Funk Forty Niner Feb 08 '20 at 20:58
  • @pet https://3v4l.org/91XZr or easier if you are using version 4 https://stackoverflow.com/q/25428361/2943403 – mickmackusa Feb 08 '20 at 22:16

1 Answers1

1

The problem is that you only initialize select2 when your document is ready. For elements that are created in the DOM afterwards, it won't automatically happen, even if they have the same class. You should reinitalize select2 for the new elements when your ajax is completed. Try this:

$.ajax({
    type: "POST",
    url: "investment_sectors.php",

    data: dataString,
    cache: false,
    success: function(html) {
        //alert(html);
        document.getElementById("sector").innerHTML = html;
        $('#' + sectorID).select2();
    }
});
Andrew
  • 827
  • 2
  • 6
  • 14
  • That makes sense, but I've added the line to initiate the select2 with the sectorID ID as you've added, but it doesn't seem to have an impact. However, I noticed that the ID tag is simply called sectorID, rather than the passed in value, which is only being used to choose the selected value if the page was editing an existing record rather than adding a brand new one. Chaning it to this seems to have worked, as the dropdrown ID ist called sectorID: $('#sectorID').select2(); – petworthnick Feb 08 '20 at 21:17
  • ...and thanks for the quick reply :-) – petworthnick Feb 08 '20 at 21:19
  • Aaah, I see, I had a brainfart and thought the id is dynamically set as the variable. I'm glad you could figure it out! – Andrew Feb 08 '20 at 21:24