简体   繁体   中英

Show hidden div on form submit (javascript & PHP)

I'm trying to create a number guessing game:

<?php
    $num = rand(1,1000);
    $guess = $_POST["guess"];
?>

<div class="intro">We've generated a random number between 1 and 100. Give us your best guess!</div>

<form action="index.php" method="post">
    <input type="text" name="guess">
    <input type="submit" value="Guess!" onsubmit="showHide()">
</form>

<div class="guess-text">Your guess was <span class="guess-var"><?php echo $guess; ?></span></div>

<div class="echo" id="hidden_div>
<?php
    if ($guess > $random) {
    echo "Sorry, too high! Better luck next number!";
    }

elseif ($guess < $random) {
echo "Sorry, too low! Better luck next number!";
    }

else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
}
?>
</div>

I want the div that displays the result

<div class="echo" id="hidden_div">

to be hidden until after the form is submitted. Here is the only code I've been able to find that helps me out:

<script type="text/javascript">
    function showHide() {
        var div = document.getElementById("hidden_div");
        if (div.style.display == 'none') {
            div.style.display = '';
        }

        else {
            div.style.display = 'none';
        }
    }
</script>

Unfortunately, this is only hiding the div. I need some help to ensure that the div will reappear after a guess is submitted. Thanks.

You can do it without using Javascript, making it cleaner...

<?php if(isset($_POST["guess"]) && $_POST["guess"]!=""){ //only show if 'guess' is posted?>
 <div class="echo" id="hidden_div>

    if ($guess > $random) {
       echo "Sorry, too high! Better luck next number!";
    }

 elseif ($guess < $random) {
 echo "Sorry, too low! Better luck next number!";
    }

 else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
 }
 ?>
 </div>
<?php } ?>

The other option is doing the output directly in Javascript so you do not need to refresh the page to get the answer.

initialy make div as hidden

<div class="echo" id="hidden_div" style="display:none">
<?php
    if ($guess > $random) {
    echo "Sorry, too high! Better luck next number!";
    }

elseif ($guess < $random) {
echo "Sorry, too low! Better luck next number!";
    }

else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
}
?>
</div>

on button click

<input type="submit" value="Guess!" id="btn" name="btn" onclick="showHide()">

<script type="text/javascript">
    function showHide() {
            document.getElementById("hidden_div").style.display = "block";
    }
</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