selectbox the option I chose goes back to the top

42 Views Asked by At

When the page is redirected, the language I chose in the box does not appear. At first, whatever is available is chosen.

here is what I want to do: change option data

<select id='lang' class='btn btn-xs btn-primary icons-select2'>
<?php
$query_lang=mysqli_query($con, "SELECT * FROM tb_lang");
while($lang = mysqli_fetch_assoc($query_lang)){
if ($lang['durum']==1)}
?>

<option value = "<?php echo $lang['lang_fix']; ?>"  data-min="_<?php echo $lang['lang_fix']; ?>" 
data-icon="<?php echo $lang['lang_flag']; ?>">
<?php
echo strtoupper($lang['lang_fix']);
?>
</option>

<?php }} ?>
</select>

<script>
$(document).ready(function () {   
  $('body').on('change','#lang', function() {
   var lang_id= $(this).val();
   window.location.replace("index.php?lang="+lang_id);
 });
});
</script>
1

There are 1 best solutions below

1
Cemal On BEST ANSWER

First retrieve the lang sent over GET by

$lang_id = $_GET['lang'];

then check it against the data you are looping through

<option value = "<?php echo $lang['lang_fix']; ?>"  data-min="_<?php echo $lang['lang_fix']; ?>" data-icon="<?php echo $lang['lang_flag']; ?>" <?php if ($lang_id == $lang['lang_fix']) echo "selected"; ?>>

making your code look like below, so the option you want to be selected will have the necessary selected attribute.

$lang_id = $_GET['lang'];
<select id='lang' class='btn btn-xs btn-primary icons-select2'>
<?php
$query_lang=mysqli_query($con, "SELECT * FROM tb_lang");
while($lang = mysqli_fetch_assoc($query_lang)){
if ($lang['durum']==1)}
?>

<option value = "<?php echo $lang['lang_fix']; ?>"  data-min="_<?php echo $lang['lang_fix']; ?>" data-icon="<?php echo $lang['lang_flag']; ?>" <?php if ($lang_id == $lang['lang_fix']) echo "selected"; ?>>
<?php
echo strtoupper($lang['lang_fix']);
?>
</option>

<?php }} ?>
</select>

<script>
$(document).ready(function () {   
  $('body').on('change','#lang', function() {
   var lang_id= $(this).val();
   window.location.replace("index.php?lang="+lang_id);
 });
});
</script>