user3627135
user3627135

Reputation: 61

Show selected value in select after page refresh

Good day. I am having a little trouble displaying the selected value in my select tag after the page has refreshed. I have 3 select tags that serves as parameters when a user wants to search for something.

 <form role="form" action="index.php" method="post">
 <select name="type" id="type">
  <option selected disabled>-- Type --</option>
  <option value="project">Project</option>
  <option value="research">Research</option>
 </select>


 <select name="status" id="status">
  <option selected disabled>-- Status --</option>
  <option value="pending">Pending</option>
  <option value="ongoing">Ongoing</option>
  <option value="disapproved">Disapproved</option>
 </select>

 <select name="budget" id="budget">
  <option selected disabled>-- Budget--</option>
  <option value="pending">Pending</option>
  <option value="for releasing">For Releasing</option>
  <option value="not required">Not Required</option>
  <option value="not released">Not Released</option>
 </select>
 <input type="submit" name="go" id="go" value="Go" />
 </form>

What I need to do is retain the selected value for each of select box or whatever the user choose after the page has loaded and has shown the results. I'm not really sure on how to accomplish this and I badly needed this feature. Please help me. Thank you in advance.

Upvotes: 1

Views: 9596

Answers (2)

Harry S
Harry S

Reputation: 256

You can use this https://github.com/carhartl/jquery-cookie

<script src="/path/to/jquery.cookie.js"></script>
<script>
$(function(){
   $(document).on('change', '#type', function(){
      $.cookie('type', $(this).val());
   });
   $(document).on('change', '#status', function(){
      $.cookie('status', $(this).val());
   });
   $(document).on('change', '#budget', function(){
      $.cookie('budget', $(this).val());
   });

  if(typeof($.cookie('type')) !== "undefined"){
     $("#type").val($.cookie('type'));
  }
  if(typeof($.cookie('status')) !== "undefined"){
     $("#status").val($.cookie('status'));
  }
  if(typeof($.cookie('budget')) !== "undefined"){
     $("#budget").val($.cookie('budget'));
  }
});
</script>

Upvotes: 2

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

First need to replace all vaue to value in form

<option vaue="pending">(vaue)

to

<option value="pending">(value)

then use php code and get your posted data with select "name" and match with options value like

<option value="project" <?php if(isset($_POST['type']) && $_POST['type'] == "project") echo 'selected="selected"';?>>Project</option>

do same match for all select options

Upvotes: 4

Related Questions