简体   繁体   中英

update the selected option in select on a condition in php

I am new to programming, what I am trying is when a user selected option from a select, the next time user visit the page or refresh the page the user will see his last selected option as selected already.

<!DOCTYPE html>
<html>
    <body>
        <select id="Example">
            <?php 
                $value = "<script>document.write(value)</script>";
                $val = "1";
                $val2 = "2";
            ?>
          <option value="1" <?php if ($val == $value){  ?>selected  <?php }  ?> >One</option>
          <option value="2" <?php if ($val2 == $value){  ?>selected <?php }  ?> >Two</option>
          <option value="3">Three</option>
        </select>
        <script>
            var sel = document.getElementById('Example');
            var value = sel.options[sel.selectedIndex].value;
        </script>   
    </body>
</html>

I am using the above code but I am not getting the desired output, please help me I am really stuck. If this is possible in JavaScript I will also be appreciated. Thanks in Advance.

Database, Cookies or localStorage

window.onload=function() {
  var val = localStorage.getItem("example"); 
  if (val) {  document.getElementById('Example').value = val } 
  document.getElementById('Example').onchange=function() { 
    localStorage.setItem("example",this.value); 
  } 
}
 <form action="" method="post">   
    <label>Country</label>     
    <select id="country" name="country" onchange="myFunction(this.value)">
        <option value="india">India</option>
        <option value="australia">Australia</option>
        <option value="canada">Canada</option>
        <option value="usa">USA</option>
    </select>
  <input type="submit" value="Submit">   
 </form>  

<script type="text/javascript">
    var val = localStorage.getItem("CountryValue"); 
    document.getElementById('country').value = val;

    // This function will store data in localstorage on client browser.
    function myFunction(value) {
        localStorage.setItem("CountryValue",value);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM