Kamran Rastegar
Kamran Rastegar

Reputation: 181

Bootstrap Select 'refresh" continues to add new options instead of removing the old ones

Any help here would be appreciated as I can't see what I'm doing wrong.

I have an empty select picker:

<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>

This is being populated via AJAX call when another select box option has changed

    var query_parameter = document.getElementById("new_deptid").value;
    var dataString = 'dept=' + query_parameter;
    
    // AJAX code to execute query and get back to same page with table content without reloading the page.
    $.ajax({
        type: "POST",
        url: "helpers/populateteams.php",
        data: dataString, 
        cache: false,
        success: function(html) {
            document.getElementById("new_teamid").innerHTML=html;
            $('#new_teamid').selectpicker('refresh');
        }
    });

As you can see, its calling another php page which returns an HTMl string for the options. This works, if i inspect the element, the HTML options are updated correctly. im using = not +=. Problem is, the selectpicker is not removing the previous items. It just keeps adding the new items.

Any idea what I may be doing wrong here?

If you are curious, this is the populateteams.php

$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';

$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);

if ($stmt->execute() === TRUE) {

    $result = $stmt->get_result();
            
    if(!empty($result) && $result->num_rows)
    {
        while ($row = mysqli_fetch_array($result)) 
        {
            $theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
        }
    }
}

echo $theHTML;

Upvotes: 2

Views: 1514

Answers (1)

Kamran Rastegar
Kamran Rastegar

Reputation: 181

resolved this myself. This is dumb, but this is how you need to do it:

$.ajax({
    type: "POST",
    url: "helpers/populateteams.php",
    data: dataString, 
    cache: false,
    success: function(html) {
        document.getElementById("new_teamid").innerHTML=html;  
        $('#new_teamid').selectpicker('destroy'); 
        $('#new_teamid').selectpicker('render'); 
    },
    complete: function(html) {
        
    }
});

You need to destroy and render instead of refresh. This is stupid. But it works

Upvotes: 4

Related Questions