每按一次提交,我想输入文本框更改文本

问题描述 投票:1回答:1

因此,基本上,我有一个简单的表单,每次使用PHP按下Submit时,我都希望更改输入框的文本。我知道我的代码行不通,但是我不明白如何解决此问题。也许数组不是执行此操作的最佳方法?

<body>
    <?php 
        if(isset($_GET['submit'])) exit();
        $msg= ['One', 'Two', 'Three', '']
    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?php echo (isset($msg)) ? $viesti : ''; ?>">
    </form>
</body>
php forms submit
1个回答
1
投票

您可以这样写:

<?php
    session_start();

    $msgArray= array('One', 'Two', 'Three', '');
    // if $_SESSION['msgIndex'] is not set, we initialize it, or it will take 0 value every loading page
    if (!isset($_SESSION['msgIndex'])) { $_SESSION['msgIndex'] = 0;  }

    if (isset($_GET['submit'])) {
        getMessage();
    }

    // We save msgIndex in a $_SESSION variable cause even if the user reload the page, we keep the value
    function getMessage() {
        if ($_SESSION['msgIndex'] >= 0) {
            $_SESSION['msgIndex'] += 1;
        } if ($_SESSION['msgIndex'] > 3) {
            $_SESSION['msgIndex'] = 0;
        }
    }
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?= $msgArray[$_SESSION['msgIndex']] ?>">
</form>
© www.soinside.com 2019 - 2024. All rights reserved.