How to display a random phrase from a list when a button is clicked on a web page?

I am creating a web page where someone can visit it. They ask a question in the field and press a button, and the answer returns to them. (Looks like a magic ball 8).

What I'm trying to do is set up something like this:

http://img585.imageshack.us/img585/997/layoutoi.png

I'm still new to manual coding stuff. I have an HTML / CSS book and one in PHP that remains unread, so I will probably need a step-by-step process. (I have a host and that's it, so I already took care.) Thanks in advance!

+3
source share
3 answers

(.. ), Javascript ( jsfiddle )

<a id="myButton" href="#">
    click here to get random stuff
</a>

<div id="myRandomDiv">
</div>

<script type="text/javascript" charset="utf-8">
    var randomStrings = [
        "hello 1",
        "hello 2",
        "hello 3", 
        "hello 4",
        "hello 5",
    ];



    var randomDiv = document.getElementById("myRandomDiv");

    document.getElementById("myButton").addEventListener("click", function() {
          randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
          newText = randomStrings[randomIndex];
          randomDiv.innerHTML = newText;
    });
</script>    

PHP ( ), :

<?php


$randomThings = array(
    'random thing 1',    
    'random thing 2',    
    'random thing 3',    
    'random thing 4',    
    'random thing 5',    
    'random thing 6',    
    'random thing 7 ',    
);

?>




<!-- REST OF YOUR PAGE -->

<?php

echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>

<!-- OTHER STUFF -->

( "" ) $randomThings.

$variableName[$index] - 0,1,2,3,4,5,6.

, ( "" ) , mt_rand 0 6, $randomThings. echo .

+3

Dorkitude - , , , , (.. $value = 'someValue), . - ( , , - ..).

, , "randomThings.txt" . Dorkitude :

<?php
    // Flags set here to ensure integrity
    $randomThings = file('responses.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

<!-- REST OF YOUR PAGE -->

<?php

    echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>
<!-- OTHER STUFF -->
+3

, PHP, javascript. , - - , php.

The javascript solution will look something like this:

<html>
  <head>
    <script type='text/javascript'>
      var answerArray = new Array("yes", "no", "maybe");

      function getAnswer() {
        document.getElementById('answerDiv').innerHTML = 
          answerArray[Math.floor(Math.random() * answerArray.length)];
      }
    </script>
  </head>
  <body>
    <input id='questionField' type='text' /><br/>
    <input type='submit' value='Ask Me!' onclick='getAnswer()' />
    <div id='answerDiv'></div>
  </body>
</html>
+2
source

Source: https://habr.com/ru/post/1786278/


All Articles