Как установить значение сеанса PHP как выбранное, щелкнув по раскрывающемуся списку - PullRequest
0 голосов
/ 13 декабря 2018

У меня есть следующий код.

<?php
     session_start();
?>
 <form action = "index.php" method = "post" name = "test">
    <!--<div id ="custom-select" style="width:200px;" onchange = "favsports()"> -->
       <div class = "custom-select">
        <div class = "select">
           <select id ="custom-select" name = "custom-select" style="width:200px;" onchange = " this.form.submit(); myFunction();">
                <option value="Abteilung auswählen" <?php if(isset($_POST['custom-select']) && $_POST['custom-select'] == 'Abteilung auswählen' || $_SESSION['custom-select'] == 'Abteilung auswählen') echo 'selected="selected" '; ?> >Abteilung auswählen</option>
                <option value="TL-311" <?php if(isset($_POST['custom-select']) && $_POST['custom-select'] == 'TL-311' || $_SESSION['custom-select'] == 'TL-311') echo 'selected="selected" '; ?> >TL-311</option>
                <option value="TP-271" <?php if(isset($_POST['custom-select']) && $_POST['custom-select'] == 'TP-271' || $_SESSION['custom-select'] == 'TP-271') echo 'selected="selected" '; ?> >TP-271</option>
                <option value="TP-310" <?php if (isset($_POST['custom-select']) && $_POST['custom-select'] == 'TP-310' || $_SESSION['custom-select'] =='TP-310') echo 'selected="selected" '; ?> >TP-310</option>
        </select>
       </div>
      </div>
 </form>
<?php

     if (isset($_POST["custom-select"]))
     {
        $_SESSION['custom-select'] = $_POST["custom-select"];
        //print_r($_SESSION);
     }

?>

Я использую один и тот же код на двух страницах, потому что выбранное значение на первой странице все равно должно быть выбрано, когда пользователь перейдет на следующую страницу.Я также использую следующий код Javascript, потому что выбранное значение должно быть сохранено и использовано на страницах.

function myFunction()
{

   var optione = '<?php echo $_SESSION['custom-select']; ?>';
     if(optione !== '')
     {
        document.getElementById("custom-select").value = optione;
     }
       document.getElementById("insert").value = optione;
       var mytext = optione;
     if (mytext == "Abteilung auswählen")
       { 
          alert("Wählen Sie bitte eine gültige Abteilung!");
          mytext = null;
          file = "TL-311";
        }
     else 
        {
          mytext = optione;
          window.file = mytext;
        }
     return window.file;
}

Код работает, но моя проблема заключается в следующем: мне нужно выбрать значение дважды перед установкой выбранногозначение, и когда я хочу изменить выбранное значение, я также должен дважды выбрать другое значение, прежде чем устанавливать его как выбранное.Может кто-нибудь сказать мне, что я делаю не так?или что на самом деле не так в моем коде?Пожалуйста, я новичок в программировании на PHP и HTML.

1 Ответ

0 голосов
/ 13 декабря 2018

Может быть, это поможет:

page1.php

<?php
    header("Content-type: text/html; charset=utf-8");
    session_start();

    // put all your elements into array
    $arr = ['Abteilung auswählen', 'TL-311', 'TP-271', 'TP-310'];
    $options = '';

    // make your options 
    foreach ($arr as $elem) {
        $options .= '<option value="'. $elem. '">'. $elem .'</option>';
    }
?>
<form action="page2.php" method = "post">
<div class = "custom-select">
    <div class = "select">
        <select id ="custom-select" name = "custom-select" style="width:200px;" onchange = " this.form.submit();">
            <?php echo $options; ?>
        </select>
    </div>
</div>

page2.php

<?php
    header("Content-type: text/html; charset=utf-8");
    session_start();

    // check POST and write in SESSION if POST isset
    // otherwise check SESSION and fill variable $custom-select

    if(isset($_POST['custom-select'])) {
        $cust_select = $_POST['custom-select'];
        $_SESSION['custom-select'] = $_POST['custom-select'];
    } else if ($_SESSION['custom-select'] && !empty($_SESSION['custom-select'])) {
        $cust_select = $_SESSION['custom-select'];
    }

    $arr = ['Abteilung auswählen', 'TL-311', 'TP-271', 'TP-310'];
    $options = '';
    foreach ($arr as $elem) {
    // here you will check if custom_element is equal to current element
    // if is equal then put 'selected' in that <option>
        if ($elem == $cust_select) {
            $selected = ' selected';
        } else {
            $selected = '';
        }
        $options .= '<option value="'. $elem. '"'.$selected.'>'. $elem .'</option>';
    }
?>


<form action="" method = "post">
    <div class = "custom-select">
        <div class = "select">
            <select id ="custom-select" name = "custom-select" style="width:200px;" onchange = " this.form.submit();">
                <?php echo $options; ?>
            </select>
        </div>
    </div>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...