Kelvin Meyer
Kelvin Meyer

Reputation: 63

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse. I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET. Here is an example of the form I have now:

<form action="" id="exampleForm" method="get">
   <input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
   </br>
   <select name="exampleList" multiple>
       <option>Apple</option>
       <option>Banana</option>
       <option>Cherry</option>
   </select>
   <input type="submit" value="Submit" id="submitButton"> </form>

I would like to keep the values of the 'exampleList' once submitted (I stay on the same page)

I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)

Upvotes: 1

Views: 3830

Answers (6)

Kelvin Meyer
Kelvin Meyer

Reputation: 63

I finally found a solution: The only flaw is the order of the :) But since I use a plugin for displaying it does not matter much.

The fix: I created 2 Array lists list1 with everying in it list2 with all selected values

Then I subtract list2 from list1 and dont have duplicates So I can print both in different print methods.

<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
    <select name="exampleList[]" multiple>
        <?php
        foreach($fruitArray as $value) {
            echo "<option value='$value'>$value</option>";
        }
        foreach($selectedFruitArray as $value) {
            echo "<option value='$value' selected>$value</option>";
        }
        ?>
    </select>
    <input type="submit">
</form>

Upvotes: 1

Winfried
Winfried

Reputation: 11553

Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.

<form action="" id="exampleForm" method="get">
    <?php 
    if (isset($_GET['exampleCheckboxStatus'])) {
        echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
    } else {
        echo '<input type="checkbox" name="exampleCheckbox"> Check this';
    ?>
    <br />
    <select name="exampleList[]" multiple>
        <?php 
        if( in_array('apple', $_GET['exampleList']) ) { 
            echo '<option value="apple" selected>Apple</option>';
        } else {
            echo '<option value="apple">Apple</option>';
        }
        if( in_array('banana', $_GET['exampleList']) ) { 
            echo '<option value="banana" selected>Banana</option>';
        } else {
            echo '<option value="banana">Banana</option>';
        }
        if( in_array('cherry', $_GET['exampleList']) ) { 
            echo '<option value="cherry" selected>Cherry</option>';
        } else {
            echo '<option value="cherry">Cherry</option>';
        }
        ?>
    </select>
    <input type="submit" value="Submit" id="submitButton"> 
</form>

Note that I added [] to the select's name and corrected the br tag.

Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.

Try it for yourself, play around with the code a bit.

Upvotes: 0

Kevin Hagenaars
Kevin Hagenaars

Reputation: 99

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
      $(document).ready(function(){
          var opts = localStorage.getItem('opts'); // get selected items from localStorage key
          opts =  opts.split(','); // split result from localstorage to array
          $('#exampleList').val(opts); // select options with array

      });
</script>
<html>
    <body>
      <select id="exampleList" multiple>
           <option value="apple">Apple</option>
           <option value="banana">Banana</option>
           <option value="cherry">Cherry</option>
       </select>
    </body>
</html>

When you POST the form you only need to write the selected option values, comma separated, to the localstorage.

Upvotes: 2

Terry
Terry

Reputation: 332

first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:

<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>

Upvotes: 0

Ghanshyam Katriya
Ghanshyam Katriya

Reputation: 1081

You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.

For e.g.,

<?php
session_start(); // Other Code
       <div>
            <p>Subtitle needs to be
                <input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
                <input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
            </p>

            <input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
        </div> //Other Code
?>

PHP Code for set value in session after submit :

<?php
session_start(); //Not required if your form action is on same page, else required  //Rest code 

$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code 
?>

Same code works for me.

Upvotes: 0

Pupil
Pupil

Reputation: 23958

Use FormRepo, a plugin specially made for retaining form data on page refreshes.

Its usage is also simple:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
    var $form = $('#input')
        , $output = $('#output')
        , repo = new FormRepo('restclient')
        ;
    // get the last submitted values back
    repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
    $form.submit(function (e) {
        // preserve the last submitted values
        repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
    });

    console.log( repo.all() );
</script>

Upvotes: 0

Related Questions