Brgerg30879
Brgerg30879

Reputation: 93

Retain selected value of the dropdown after page refreshes

I need to retain selected value of the dropdown after page refreshes on click.

What is happening:

After I select an item from the dropdown the page reloads by itself and the value of the dropdown go to starting position though the value displays on the end of the url.

This is my code:

<script>
function refreshPage(passValue){
    window.location="index.php?cat_page=admin_post&sw_cat=sw_catn="+passValue;
}
</script>


<div class="form-group col-md-4">
    <label for="inputState">Your health proplem</label>
    <select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php 
while(mysqli_stmt_fetch($stmt)){
    echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
    </select>
</div>

This option doesn't work too:

<script>
var selectedItem = sessionStorage.getItem("SelectedItem");  
$('#dropdown').val(selectedItem);

$('#dropdown').change(function() { 
    var dropVal = $(this).val();
    sessionStorage.setItem("SelectedItem", dropVal);
});
</script>

<div class="form-group col-md-4">
    <label for="inputState">Your health proplem</label>
    <select name="illness_id_cat" class="form-control" id="dropdown" >
<?php 
while(mysqli_stmt_fetch($stmt)){
    echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
    </select>
</div>

This I don't know how to implement, what is a "itemname":

<script>
var text = localStorage.getItem("itemname");
if(text !== null) {
    $("select option").filter(function() {
        return this.text == text;
    }).attr('selected', true);
}
</script>

Upvotes: 0

Views: 284

Answers (1)

ADyson
ADyson

Reputation: 61904

A more conventional way to do this would be using PHP, and getting the querystring value you're passing in via the window.location command:

<script>
function refreshPage(passValue){
    window.location="index.php?cat_page=admin_post&sw_cat="+passValue;
}
</script>


<div class="form-group col-md-4">
    <label for="inputState">Your health problem</label>
    <select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php 
while(mysqli_stmt_fetch($stmt)){
    echo "<option";
    //get the category value from the querystring and check it against the current category value in the loop. If it matches, pre-set the option as selected
    if (isset($_GET["sw_cat"])) {
      if ($_GET["sw_cat"] == $illness_id_cat) echo " selected";
    }
    echo " value='{$illness_id_cat}'>{$illness_name_cat}</option>";

}
?>
    </select>
</div>

Upvotes: 1

Related Questions